ADO.Net 浅析(二)
上集回顾: 上集主要写了ADO.net是什么的问题,并用一个简单的实例解释了如何使用datareader来读取数据库.
其中涉及到了, datareader的索引器的使用,罗列datacommand操作数据库的几个方法,最后给出了几个常用的connectionstring的写法
续上一回提到的异步操作,代码如下
private void AsynReader(string connectionString)
{
SqlCommand command = null;
SqlConnection connection = new SqlConnection(connectionString);
command = new SqlCommand("SELECT top 5 * FROM t_Customer_BaseInfo;",
connection);
connection.Open();
Console.WriteLine("Executing");
AsyncCallback callback = new AsyncCallback(HandleCallback);
command.BeginExecuteReader(callback, command);
Console.WriteLine("Executed");
}
private void HandleCallback(IAsyncResult result)
{
SqlCommand command = (SqlCommand)result.AsyncState;//启动异步操作的方法的最后一个参数的类型实例.
SqlDataReader reader = command.EndExecuteReader(result);
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
{
SqlCommand command = null;
SqlConnection connection = new SqlConnection(connectionString);
command = new SqlCommand("SELECT top 5 * FROM t_Customer_BaseInfo;",
connection);
connection.Open();
Console.WriteLine("Executing");
AsyncCallback callback = new AsyncCallback(HandleCallback);
command.BeginExecuteReader(callback, command);
Console.WriteLine("Executed");
}
private void HandleCallback(IAsyncResult result)
{
SqlCommand command = (SqlCommand)result.AsyncState;//启动异步操作的方法的最后一个参数的类型实例.
SqlDataReader reader = command.EndExecuteReader(result);
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
其中 connstr如下
string asynconnstr="Server=myServerAddress;Database=myDataBase;Integrated Security=True;Asynchronous Processing=True;"