asp数据库查询⽅法总结摘
"ado 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();asp数据
SqlCommand cmd = new SqlCommand(strSQL, cn);
if (cmd.ExecuteNonQuery())
Console.WriteLine ("Update succeede");
else
Console.WriteLine("Update failed");
对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的⾏数。对于所有其他类型的语句,返回值为 -1。如果发⽣回滚,返回值也为 -1
//执⾏批量操作查询
//执⾏获取XML数据的查询
//在事务中执⾏查询
//异步执⾏查询
"

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。