转自:http://msdn.microsoft.com/zh-cn/library/dw70f090

本主题中的代码列表演示如何使用下面的 ADO.NET 技术从数据库中检索数据:

以下代码列表演示如何使用 ADO.NET 数据提供程序从数据库中检索数据。 数据在一个 DataReader 中返回。 有关更多信息,请参见使用 DataReader 检索数据

SqlClient

此示例中的代码假定您可以连接到 Microsoft SQL Server 的 Northwind 示例数据库。 在此情形 5 中,示例代码创建一个 SqlCommand 以从 Products 表中选择行,并添加SqlParameter 来将结果限制为其 UnitPrice 大于指定参数值的行。 SqlConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源。 示例代码使用SqlDataReader 执行命令,并在控制台窗口中显示结果。

 
using System;
using System.Data;
using System.Data.SqlClient; class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true"; // Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > @pricePoint "
+ "ORDER BY UnitPrice DESC;"; // Specify the parameter value.
int paramValue = 5; // Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue); // Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}

[返回页首]

OleDb

此示例中的代码假定您可以连接到 Microsoft Access Northwind 示例数据库。 在此情形 5 中,示例代码创建一个 OleDbCommand 以从 Products 表中选择行,并添加一个OleDbParameter 来将结果限制为其 UnitPrice 大于指定参数值的行。 OleDbConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源。 示例代码使用OleDbDataReader 执行命令,并在控制台窗口中显示结果。

 
using System;
using System.Data;
using System.Data.OleDb; class Program
{
static void Main()
{
// The connection string assumes that the Access
// Northwind.mdb is located in the c:\Data folder.
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;User Id=admin;Password=;"; // Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;"; // Specify the parameter value.
int paramValue = 5; // Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
// Create the Command and Parameter objects.
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue); // Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}

[返回页首]

Odbc

此示例中的代码假定您可以连接到 Microsoft Access Northwind 示例数据库。 在此情形 5 中,示例代码创建一个 OdbcCommand 以从 Products 表中选择行,并添加一个OdbcParameter 来将结果限制为其 UnitPrice 大于指定参数值的行。 OdbcConnection 在 using 块内打开,这将确保在代码退出时会关闭和释放资源。 示例代码使用OdbcDataReader 执行命令,并在控制台窗口中显示结果。

 
using System;
using System.Data;
using System.Data.Odbc; class Program
{
static void Main()
{
// The connection string assumes that the Access
// Northwind.mdb is located in the c:\Data folder.
string connectionString =
"Driver={Microsoft Access Driver (*.mdb)};"
+ "Dbq=c:\\Data\\Northwind.mdb;Uid=Admin;Pwd=;"; // Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;"; // Specify the parameter value.
int paramValue = 5; // Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// Create the Command and Parameter objects.
OdbcCommand command = new OdbcCommand(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue); // Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}

[返回页首]

OracleClient

此示例中的代码假定已建立与 Oracle 服务器上的 DEMO.CUSTOMER 的连接。 您还必须添加对 System.Data.OracleClient.dll 的引用。 示例代码在 OracleDataReader 中返回数据。

 
using System;
using System.Data;
using System.Data.OracleClient; class Program
{
static void Main()
{
string connectionString =
"Data Source=ThisOracleServer;Integrated Security=yes;";
string queryString =
"SELECT CUSTOMER_ID, NAME FROM DEMO.CUSTOMER";
using (OracleConnection connection =
new OracleConnection(connectionString))
{
OracleCommand command = connection.CreateCommand();
command.CommandText = queryString; try
{
connection.Open(); OracleDataReader reader = command.ExecuteReader(); while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}",
reader[0], reader[1]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

[返回页首]

以下代码列表演示如何通过查询实体数据模型 (EDM) 中的实体来从数据源检索数据。 这些示例使用 Northwind 模型。 有关更多信息,请参见实体框架概述

LINQ to Entities

此示例中的代码使用 LINQ 查询以 Categories 对象的形式返回数据,这些对象将作为仅包含 CategoryID 和 CategoryName 属性的匿名类型提取。 有关更多信息,请参见LINQ to Entities Overview

 
 
Option Explicit On
Option Strict On Imports System
Imports System.Linq
Imports System.Data.Objects
Imports NorthwindModel Class LinqSample
Public Shared Sub ExecuteQuery()
Using context As NorthwindEntities = New NorthwindEntities()
Try
Dim query = From category In context.Categories _
Select New With _
{ _
.categoryID = category.CategoryID, _
.categoryName = category.CategoryName _
} For Each categoryInfo In query
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
categoryInfo.categoryID, categoryInfo.categoryName)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class

在 C# 中:

 
 
using System;
using System.Linq;
using System.Data.Objects;
using NorthwindModel; class LinqSample
{
public static void ExecuteQuery()
{
using (NorthwindEntities context = new NorthwindEntities())
{
try
{
var query = from category in context.Categories
select new
{
categoryID = category.CategoryID,
categoryName = category.CategoryName
}; foreach (var categoryInfo in query)
{
Console.WriteLine("\t{0}\t{1}",
categoryInfo.categoryID, categoryInfo.categoryName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

[返回页首]

类型化 ObjectQuery

此示例中的代码使用 ObjectQuery<T> 以 Categories 对象的形式返回数据。 有关更多信息,请参见Object Queries (Entity Framework)

 
 
Option Explicit On
Option Strict On Imports System
Imports System.Data.Objects
Imports NorthwindModel Class ObjectQuerySample
Public Shared Sub ExecuteQuery()
Using context As NorthwindEntities = New NorthwindEntities()
Dim categoryQuery As ObjectQuery(Of Categories) = context.Categories For Each category As Categories In _
categoryQuery.Execute(MergeOption.AppendOnly)
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
category.CategoryID, category.CategoryName)
Next
End Using
End Sub
End Class

在 C# 中:

 
 
using System;
using System.Data.Objects;
using NorthwindModel; class ObjectQuerySample
{
public static void ExecuteQuery()
{
using (NorthwindEntities context = new NorthwindEntities())
{
ObjectQuery<Categories> categoryQuery = context.Categories; foreach (Categories category in
categoryQuery.Execute(MergeOption.AppendOnly))
{
Console.WriteLine("\t{0}\t{1}",
category.CategoryID, category.CategoryName);
}
}
}
}

[返回页首]

EntityClient

此示例中的代码使用 EntityCommand 来执行实体 SQL 查询。 此查询会返回表示 Categories 实体类型的实例的记录的列表。 EntityDataReader 用于访问结果集中的数据记录。 有关更多信息,请参见用于实体框架的 EntityClient 提供程序

 
 
Option Explicit On
Option Strict On Imports System
Imports System.Data
Imports System.Data.Common
Imports System.Data.EntityClient
Imports NorthwindModel Class EntityClientSample
Public Shared Sub ExecuteQuery()
Dim queryString As String = _
"SELECT c.CategoryID, c.CategoryName " & _
"FROM NorthwindEntities.Categories AS c" Using conn As EntityConnection = _
New EntityConnection("name=NorthwindEntities") Try
conn.Open()
Using query As EntityCommand = _
New EntityCommand(queryString, conn)
Using rdr As DbDataReader = _
query.ExecuteReader(CommandBehavior.SequentialAccess)
While rdr.Read()
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
rdr(0), rdr(1))
End While
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class

在 C#" 中

 
 
using System;
using System.Data;
using System.Data.Common;
using System.Data.EntityClient;
using NorthwindModel; class EntityClientSample
{
public static void ExecuteQuery()
{
string queryString =
@"SELECT c.CategoryID, c.CategoryName
FROM NorthwindEntities.Categories AS c"; using (EntityConnection conn =
new EntityConnection("name=NorthwindEntities"))
{
try
{
conn.Open();
using (EntityCommand query = new EntityCommand(queryString, conn))
{
using (DbDataReader rdr =
query.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (rdr.Read())
{
Console.WriteLine("\t{0}\t{1}", rdr[0], rdr[1]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

[返回页首]

此示例中的代码使用 LINQ 查询以 Categories 对象的形式返回数据,这些对象将作为仅包含 CategoryID 和 CategoryName 属性的匿名类型提取。 此示例基于 Northwind 数据上下文。 有关更多信息,请参见入门

 
 
Option Explicit On
Option Strict On Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Northwind Class LinqSqlSample
Public Shared Sub ExecuteQuery()
Using db As NorthwindDataContext = New NorthwindDataContext()
Try
Dim query = From category In db.Categories _
Select New With _
{ _
.categoryID = category.CategoryID, _
.categoryName = category.CategoryName _
} For Each categoryInfo In query
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}", _
categoryInfo.categoryID, categoryInfo.categoryName)
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
End Class

在 C# 中:

 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Northwind; class LinqSqlSample
{
public static void ExecuteQuery()
{
using (NorthwindDataContext db = new NorthwindDataContext())
{
try
{
var query = from category in db.Categories
select new
{
categoryID = category.CategoryID,
categoryName = category.CategoryName
}; foreach (var categoryInfo in query)
{
Console.WriteLine("vbTab {0} vbTab {1}",
categoryInfo.categoryID, categoryInfo.categoryName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

[返回页首]

ADO.NET 代码示例的更多相关文章

  1. 高级渲染技巧和代码示例 GPU Pro 7

    下载代码示例 移动设备正呈现着像素越来越高,屏幕尺寸越来越小的发展趋势. 由于像素着色的能耗非常大,因此 DPI 的增加以及移动设备固有的功耗受限环境为降低像素着色成本带来了巨大的压力. MSAA 有 ...

  2. Java8-Function使用及Groovy闭包的代码示例

    导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...

  3. [IOS 开发] 懒加载 (延迟加载) 的基本方式,好处,代码示例

    懒加载的好处: 1> 不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强 2> 每个属性的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合 ...

  4. SELECT控件操作的JS代码示例

    SELECT控件操作的JS代码示例 1 检测是否有选中 if(objSelect.selectedIndex > -1) { //说明选中 } else { //说明没有选中 } 2.动态创建s ...

  5. 转:HIBERNATE一些_方法_@注解_代码示例---写的非常好

    HIBERNATE一些_方法_@注解_代码示例操作数据库7步骤 : 1 创建一个SessionFactory对象 2 创建Session对象 3 开启事务Transaction : hibernate ...

  6. Python实现各种排序算法的代码示例总结

    Python实现各种排序算法的代码示例总结 作者:Donald Knuth 字体:[增加 减小] 类型:转载 时间:2015-12-11我要评论 这篇文章主要介绍了Python实现各种排序算法的代码示 ...

  7. C#与数据库访问技术总结(十五)之 DataAdapter对象代码示例

    DataAdapter对象代码示例 下面的代码将说明如何利用DataAdapter对象填充DataSet对象. private static string strConnect=" data ...

  8. C#与数据库访问技术总结(六)之Command对象创建SQl语句代码示例

    Command对象创建SQl语句代码示例 说明:前面介绍了 Command 对象的方法和一些属性,回顾一下 Command对象主要用来执行SQL语句.利用Command对象,可以查询数据和修改数据. ...

  9. 领域驱动开发推荐代码示例 — Microsoft NLayerApp

    简介: Microsoft NLayerApp是由微软西班牙团队出品的基于.NET 4.0的“面向领域N层分布式架构”代码示例,在codeplex上的地址是:http://microsoftnlaye ...

随机推荐

  1. nginx 代理 proxy_pass设置

    #img.test.com/img1 实际访问的路径是 http://127.0.0.1:123/a1 #img.test.com/img2 实际访问的路径是 http://127.0.0.1:123 ...

  2. Nginx(一)初始环境的安装(php5.3+mysql5.1+fastcgi…)

    关参考资源http://www.lnmp.org/index.html \\LNMP一键安装包http://www.howtocn.org/nginx \\Nginx模块参考手册中文版http://b ...

  3. shell实现查询oracle数据库表,并写到本地txt文件

    1.表结构 create table t_student( id ) primary key, name ), birthday date ); increment ; insert into t_s ...

  4. ECMAScript一元操作符

    在ECMAScript中提供了一元操作符进行简单的运算,一元操作符是ECMAScript中最简单的操作符,它只能对一个值进行操作. 一元操作符有两种类型,一种是递增和递减操作符,一种是一元加和一元减操 ...

  5. 在 lamp(centos)下配置二级 域名 、虚拟主机

    1.你得拥有一个泛域名解析的顶级域名,有一个独立的IP: 2.解析二级域名,如在万网中心里,记录类型为A, 主机记录即为要配的二级域名(如:增加两个:bbs.mydomain.com 和 www.my ...

  6. MVC中Razor视图基本语法(1)

    Razor前面,必须要跟前面的有空隙,即空格(多谢一楼提醒,url里面确实不用空格,如果要在url里面只需要@(ViewBag.),加上括号就好了),之后的必须要连贯,否则加小括号 1,在页面中输出单 ...

  7. demo_06Canvas

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  8. Omnithreadlibary学习(1)-异步执行

    program main; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, OtlParallel; begin Parallel.Async( ...

  9. python开发-web框架之diango-----Models

    这篇博客是紧连上一篇博客的,因为内容较多,这里介绍的是Models这一部分的内容 七:Models 数据库的配置 1    django默认支持sqlite,mysql, oracle,postgre ...

  10. Forget asp.net membership,ASP.NET Identity Overview

    http://www.asp.net/identity http://www.asp.net/identity/overview/getting-started/introduction-to-asp ...