如果程序需要执行面向集合的操作,比如删除、更新所有的满足某一条件的行,则直接使用单一的SQL命令要比使用在C#代码中扩展的SQL命令要更有效,尤其对于大型标来说更是如此。ADO.NET提供SqlCommand和OleCommand对象,以执行SQL命令。这些对象提供Execute()方法执行SQL命令。前面介绍DataReader对象时已经使用ExecuteReader()方法。下面介绍其他的Execute()方法:
1.SqlCommand的ExecuteScalar方法执行查询:此方法用于执行仅仅返回一个标量的SQL命令(标量即单一值,相对于ExecuteReader()所返回的多行)。下面程序获取表的行数:
using System;
using System.Data;
using System.Data.SqlClient;
class DataExcuteScalarExample
{
public static void Main()
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=(local);User Id=sa;Password=sa;Integrated Security=SSPI;Initial Catalog=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT COUNT(*) FROM Customers";
Object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers={0}",countResult);
thisConnection.Close;
}
}
2.SqlCommand的ExecuteNonQuery方法执行根本就不返回任何数据的命令。如Insert、Update、Delete的数据修改操作不返回任何数据,只返回受影响的行数。下面程序为将一个供应商的产品价格上涨5%。
using System;
using System.Data;
using System.Data.SqlClient;
class DataSqlNonQueryExample
{
public static void Main()
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=(local);User Id=sa;Password=sa;Integrated Security=SSPI;Initial Catalog=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Update Products Set UnitPrice=UnitPrice*1.05 Where SupplierId=12";
int rowsAffected = thisCommand.ExecuteNonQurey();
Console.WriteLine("Rows Update={0}", rowsAffected);
thisConnection.Close;
}
}
<注:>本文参考文献
《C#入门经典》清华大学出版社