4.1在代码中使用SqlCommand对象
4.1.1创建sqlCommand对象
//不使用参数创建
sqlCommand cmd;
cmd = new sqlCommand();
cmd.Connection = cn;
cmd.CommandText = strSQL;
//使用参数来构造
sqlCommand cmd = new sqlCommand( strSQL.cn);
//用connection的CreateCommand来构造
cmd = cn.CreateCommand();
cmd.CommandText = strSQL;
4.1.3 执行返回行的查询
sqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "select * From ...";
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
Console.Write(dr["UserName"]);
4.1.4 获取单一值
strSQL = "select count(*) from tabname";
sqlCommandText = new sqlCommand(strSQL,cn);
int icount = (int)cmd.ExecuteScalar();
4.1.5执行不返回结果集的查询
strSQL ="Update table set field01=100"
sqlCommand cmd = new sqlCommand(strSQL,cn);
int iRow= cmd.ExecuteNonQuery(); //返回值是受影响的行数,反应执行成功的情况
4.1.6 执行批量操作查询
strSQL ="update table01 set field01 =001 .." +
"update table02 set field01 =002 .." +
"update table03 set field01 =003 .."
sqlCommand cmd = new sqlCommand(strSQL,cn);
int icount = cmd.ExecuteNonQuery();//返回各个查询所修改的总行数,
利用StatementCompleted事件可以确定批量操作中各个查询所修改的行数
sqlCommand cmd = new sqlCommand(strSQL,cn);
cmd.StatementCompleted += new StatementCompletedEventHandler(HandleStatementCompleted);
int irow = cmd.ExcuteNonQuery();
static void HandleStatementCompleted(object sender,StatementCompletedEventArgs e)
{
int row = e.RecordCount;//这里能反应出每个查询受影响的行数
}