"ado.net 2.0 技术内幕
执行返回行的查询
使用到的类和方法: SqlConnection, SqlCommand, ExecuteReader, SqlDataReader
ExecuteReader方法返回一个SqlDataReader对象, SqlDataReader对象查看结果中的一行数据, 并且是单向的
例子:
string strConn, strSQL;
strConn = @" Data Source=.\SQLExpress; " + " Initial Catalog=Northwind;Trusted_Connection=Yes; " ;
strSQL = " SELECT OrderID, CustomerID, OrderDate " +" FROM Orders WHERE Shipcountry = 'Canada' " ;
SqlConnection cn = new SqlConnection(strConn);
cn.Open();
SqlCommand cmd = new SqlCommand(strSQL, cn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
Console.WriteLine( " {0} {1} {2:d} " , rdr[ " OrderID " ], rdr " CustomerID " ], rdr[ " OrderDate " ]);
rdr.Clode();
获取单一值
使用到的类和方法: SqlConnection, SqlCommand, ExecuteScalar
ExecuteScalar方法不是返回一个SqlDataReader, 而是返回在一般Object数据类型中第一行第一列的值。在希望返回单一值的时候, 可以使用这个语法甜头, 虽然它也创建了SqlDataReader, 并获取期望值, 但不去要编写全部代码
例子:
string strConn, strSQL;
strConn = @" Data Source=.\SQLExpress; " + " Initial Catalog = Northwing;Trusted_Connection=Yes; " ;
strSQL = " SELECT SUM(UnitPrice * Quantity) " +
" FROM Orders INNER JOIN [Order Details] " +
" ON Orders.OrderID = [Order Details].OrderID " +
" WHERE CustomerID -'ALFKI' " ;
sqlConnertion cn = new SqlConnection(strConn);
cn.Open();
SqlCommand cmd = new SqlCommand(strSQL, cn);
decimal decOrderTotal = ( decimal )cmd.ExecuteScalar();
Console.WriteLine( " Order Total: {0:c} " , decOrderTotal);
decimal是SQL Server的浮点数类型格式, ":c"是使用系统的货币格式格式化输出
执行不返回结果集的查询(数据更新修改)
使用到的类和方法: SqlConnection, SqlCommand, ExecuteNonQuery
可以通过调用SqlCommand的ExecuteReader方法来执行这些查询。但是因为这些查询不返回任何行, 所以似乎是一些不必要的开销。幸运的是, 还有更简单的方法, SqlCommand类公开了ExecuteNonQuery方法, 该方法执行查询而不返回SqlDataReader对象
例子:
string strConn, strSQL;
strConn = @" Data Source=.\SQLExpress; " + " Initial Catalog=Northwind;Trusted_Connection=Yes; " ;
strSQL = " UPDATE Customers SET CompanyName = 'NewValue' " +
" WHERE CustomerID = 'ALFKI' " ;
SqlConnection cn = new SqlConnection(strConn);
cn.Open();
SqlCommand cmd = new SqlCommand(strSQL, cn);
if (cmd.ExecuteNonQuery())
Console.WriteLine ( " Update succeede " );
else
Console.WriteLine( " Update failed " );
对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也为 -1
//执行批量操作查询
//执行获取XML数据的查询
//在事务中执行查询
//异步执行查询
"