datareader对象提供只读单向数据的快速传递,单向:您只能依次读取下一条数据;只读:DataReader中的数据是只读的,不能修改;相对地,DataSet中的数据可以任意读取和修改
01.using (SqlConnection connection =
02. new SqlConnection(connectionString))
03.{
04. SqlCommand command =
05. new SqlCommand(queryString, connection);
06. connection.Open();
07.
08. SqlDataReader reader = command.ExecuteReader();
09.
10. // 判断数据是否读到尾.
11. while (reader.Read())
12. {
13. Console.WriteLine(String.Format("{0}, {1}",
14. reader[0], reader[1]));
15. }
16.
17. // 一定要关闭 reader 对象.
18. reader.Close();
19.}
SqlDataReader对象GetOrdinal()方法可以查看序列号的值
01.SqlCommand cmd = new SqlCommand();
02.//存储过程应用
03.cmd.Connection = conn;
04.cmd.CommandType = CommandType.StoredProcedure;
05.cmd.CommandText = "ListTable";
06.cmd.Parameters.AddWithValue("@fileName", "ClsName, Sort");
07.cmd.Parameters.AddWithValue("@tableName", "Class");
08.cmd.Parameters.AddWithValue("@Sort", null);
09.cmd.Parameters.AddWithValue("@whereStr", "ID < 10");
10.cmd.Parameters.AddWithValue("@groupStr", null);
11.SqlDataReader rdr = cmd.ExecuteReader();
12.int intClsName = rdr.GetOrdinal("ClsName");
13.int intSort = rdr.GetOrdinal("Sort");
14.
15.while (rdr.Read())
16.{
17. Console.WriteLine("ClsName : {0}, Sort:{1}", rdr[intClsName], rdr[intSort]);
18. //可以调用SqlDataReader 的 Get 方法来避免由于装箱,拆箱而导致的性能损失
19. Console.WriteLine("ClsName : {0}, Sort:{1}", rdr.GetString(intClsName), rdr.GetInt32(intSort));
20. //调用SqlDataReader 的 Get 方法在碰到 NULL 值时将会产生一个 SqlNullValueException.可以使用IsDBNull方法判断
21. articleClass arc = new articleClass();
22. arc.clsname = rdr[0];
23. if (rdr.IsDBNull(rdr[1]))
24. arc.sort = null;
25. else
26. arc.sort = rdr[1];
27. arc.clsname = rdr[1];
28. arc.Add(arc);
29.}
30.rdr.Close();
C# 数据库使用SqlCommand进行增,删,改,查询操作
using System;
using System.Collections.Generic;
using System.Text;
// We will make use of the SQL server
// provider, however it would also be
// permissible to make use of the ADO.NET
// factory pattern for greater flexibility.
using System.Data;
using System.Data.SqlClient;
namespace AutoLotConnectedLayer
{
public class InventoryDAL
{
#region Connection and Disconnection details.
// This member will be used by all methods.
private SqlConnection sqlCn = new SqlConnection();
public void OpenConnection(string connectionString)
{
sqlCn.ConnectionString = connectionString;
sqlCn.Open();
}
public void CloseConnection()
{
sqlCn.Close();
}
#endregion
#region Insert logic (both versions)
//public void InsertAuto(int id, string color, string make, string petName)
//{
// // Format and execute SQL statement.
// string sql = string.Format("Insert Into Inventory" +
// "(CarID, Make, Color, PetName) Values" +
// "('{0}', '{1}', '{2}', '{3}')", id, make, color, petName);
//
// // Execute using our connection.
// using(SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
// {
// cmd.ExecuteNonQuery();
// }
//}
public void InsertAuto(int id, string color, string make, string petName)
{
// Note the 'placeholders' in the SQL query.
string sql = string.Format("Insert Into Inventory" +
"(CarID, Make, Color, PetName) Values" +
"(@CarID, @Make, @Color, @PetName)");
// This command will have internal parameters.
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
// Fill params collection.
SqlParameter param = new SqlParameter();
param.ParameterName = "@CarID";
param.Value = id;
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@Make";
param.Value = make;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@Color";
param.Value = color;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);
param = new SqlParameter();
param.ParameterName = "@PetName";
param.Value = petName;
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
}
#endregion
#region Delete logic
public void DeleteCar(int id)
{
// Get ID of car to delete, then do so.
string sql = string.Format("Delete from Inventory where CarID = '{0}'",
id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Exception error = new Exception("Sorry! That car is on order!", ex);
throw error;
}
}
}
#endregion
#region Update logic
public void UpdateCarPetName(int id, string newPetName)
{
// Get ID of car to modify and new pet name.
string sql =
string.Format("Update Inventory Set PetName = '{0}' Where CarID = '{1}'",
newPetName, id);
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
cmd.ExecuteNonQuery();
}
}
#endregion
#region Select logic
public DataTable GetAllInventory()
{
// This will hold the records.
DataTable inv = new DataTable();
// Prep command object.
string sql = "Select * From Inventory";
using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
{
SqlDataReader dr = cmd.ExecuteReader();
// Fill the DataTable with data from the reader and clean up.
inv.Load(dr);
dr.Close();
}
return inv;
}
#endregion
#region Trigger stored proc logic
public string LookUpPetName(int carID)
{
string carPetName = string.Empty;
// Establish name of stored proc.
using (SqlCommand cmd = new SqlCommand("GetPetName", this.sqlCn))
{
cmd.CommandType = CommandType.StoredProcedure;
// Input param.
SqlParameter param = new SqlParameter();
param.ParameterName = "@carID";
param.SqlDbType = SqlDbType.Int;
param.Value = carID;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);
// Output param.
param = new SqlParameter();
param.ParameterName = "@petName";
param.SqlDbType = SqlDbType.Char;
param.Size = 10;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
// Execute the stored proc.
cmd.ExecuteNonQuery();
// Return output param.
carPetName = ((string)cmd.Parameters["@petName"].Value).Trim();
}
return carPetName;
}
#endregion
#region Tx Method
// A new member of the InventoryDAL class.
public void ProcessCreditRisk(bool throwEx, int custID)
{
// First, look up current name based on customer ID.
string fName = string.Empty;
string lName = string.Empty;
SqlCommand cmdSelect = new SqlCommand(
string.Format("Select * from Customers where CustID = {0}", custID), sqlCn);
using (SqlDataReader dr = cmdSelect.ExecuteReader())
{
while (dr.Read())
{
fName = (string)dr["FirstName"];
lName = (string)dr["LastName"];
}
}
// Create command objects which represent each step of the operation.
SqlCommand cmdRemove = new SqlCommand(
string.Format("Delete from Customers where CustID = {0}", custID), sqlCn);
SqlCommand cmdInsert = new SqlCommand(string.Format("Insert Into CreditRisks" +
"(CustID, FirstName, LastName) Values" +
"({0}, '{1}', '{2}')", custID, fName, lName), sqlCn);
// We will get this from the Connection object.
SqlTransaction tx = null;
try
{
tx = sqlCn.BeginTransaction();
// Enlist the commands into this transaction.
cmdInsert.Transaction = tx;
cmdRemove.Transaction = tx;
// Execute the commands.
cmdInsert.ExecuteNonQuery();
cmdRemove.ExecuteNonQuery();
// Simulate error.
if (throwEx)
{
throw new ApplicationException("Sorry! Database error! Tx failed...");
}
// Commit it!
tx.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Any error will rollback transaction.
tx.Rollback();
SqlCommand 对象的 ExecuteScalar 方法返回一个 Object 数据类型中第一行第一列的值。
view plaincopy to clipboardprint?
01.SqlCommand cmd = new SqlCommand();
02.//存储过程应用
03.cmd.Connection = conn;
04.cmd.CommandType = CommandType.StoredProcedure;
05.cmd.CommandText = "ListTable";
06.cmd.Parameters.AddWithValue("@fileName", "top 1 ID");
07.cmd.Parameters.AddWithValue("@tableName", "Class");
08.cmd.Parameters.AddWithValue("@Sort", null);
09.cmd.Parameters.AddWithValue("@whereStr", "ID < 4");
10.cmd.Parameters.AddWithValue("@groupStr", null);
11.//可以直接使用 object Obj = cmd.ExecuteScalar(); 然后判断 Obj == null 并进行下步操作
12.int ClassID = (int)cmd.ExecuteScalar();
13.Console.WriteLine(ClassID);
ExecuteNonQuery执行不返回结果集的查询,SqlCommand 对象的 ExecuteNonQuery 方法
view plaincopy to clipboardprint?
01.string UPDATE_SP = "update class set clsname = @ClassName where id = @ClassID";
02.SqlCommand cmd = new SqlCommand(UPDATE_SP, conn);
03.SqlParameter[] p = new SqlParameter[2]{
04. new SqlParameter("@ClassName", DbType.String),
05. new SqlParameter("@ClassID", DbType.Int32)
06.};
07.p[0].Value = "Ado.Net";
08.p[1].Value = 7;
09.
10.foreach (SqlParameter parm in p)
11. cmd.Parameters.Add(p);
12.
13.int ExecuteNum = cmd.ExecuteNonQuery();
14.Console.WriteLine(ExecuteNum);
Parameters参数化查询
,上述代码中已经实现参数化查询。Parameters 的作用可有效防止注入。利用AddWithValue 方法把参数传递给 cmd 对象。SqlParameter 对象详解
view plaincopy to clipboardprint?
01.//SqlParameter 对象,利用SqlCommand AddWithValue方法创建 同等于下面
02.cmd.Parameters.AddWithValue("@ClassID", 3);
03.
04.//SqlParameter 对象
05.SqlParameter p = new SqlParameter("@ClassID", DbType.Int16);
06.p.Value = 3;
07.cmd.Parameters.Add(p);
批量操作查询
,用StatementCompleted事件获取批量操作查询时个语句返回的影响数
view plaincopy to clipboardprint?
01.static void HandleStatementCompleted(object sender, StatementCompletedEventArgs e)
02.{
03. Console.WriteLine("查询影响:{0} row(s)", e.RecordCount);
04.}
05.//..........................................
06.string SQL = "update class set num = 1 where id = 3;" +
07. "update class set num = 2 where id = 4;" +
08. "update class set num = 3 where id = 5;" +
09. "update class set num = 4 where id = 6;";
10.SqlCommand cmd = new SqlCommand(SQL, conn);
11.cmd.StatementCompleted += new StatementCompletedEventHandler(HandleStatementCompleted);
12.int ExecuteNum = cmd.ExecuteNonQuery();
13.Console.WriteLine("批量查询共影响:{0} row(s)", ExecuteNum);
14.
15.//输出来自查询的多个结果集
16.do {
17. while (rdr.Read())
18. Console.WriteLine("{0} - {1}", rdr[0], rdr[1]);
19.
20.} while (rdr.NextResult());
执行异步查询,SqlCommand公开了Begin, End方法,例如:BeginExecuteReader, EndExecuteReader方法
每个 Begin 方法返回一个实现 IAsyncResult 接口对象。这一返回对象是查询状态的一个句柄,IAsyncResult 接口是用于异步方法的.NET Framework 模式的一部分,其设计目的:帮助确定该操作是否已经完成如果需要等待该操作完成则中断当前线程;用作方法调用的句柄。 IAsyncResult 接口的IsCompleted 属性,以查看 BeginExecuteReader 调用是否已经完成。调用IAsyncResult.AsyncWaitHandle.WaitOne 使用IAsyncResult接口来等待该调用完成 。
view plaincopy to clipboardprint?
01.using System.Threading; //需引用此命名空间
02.
03.conn.Open();
04.string SQL = "waitfor delay '00:00:10' ;" +
05. "select * from class";
06.SqlCommand cmd = new SqlCommand(SQL, conn);
07.IAsyncResult iar = cmd.BeginExecuteReader();
08.Console.WriteLine("异步查询是否已经获取记录?");
09.while (!iar.IsCompleted)
10.{
11. Console.WriteLine("否,还在等待.");
12. iar.AsyncWaitHandle.WaitOne(1000, true);
13.}
14.Console.WriteLine("是,已经获取数据.");
15.
16.SqlDataReader rdr = cmd.EndExecuteReader(iar);
17.while (rdr.Read())
18.{
19. Console.WriteLine(rdr["ClsName"]);
20.}
21.rdr.Close();