Typed DataSet的批量操作优化
通过vs自动生成的强类型dataset代码,我截取看了一段自动生成的代码
//以下代码是我自定义了一段update 操作vs自动生成的
public virtual int ResetErrortimes(int id) {
global::System.Data.SqlClient.SqlCommand command =
this.CommandCollection[3];
command.Parameters[0].Value = ((int)(id));
global::System.Data.ConnectionState previousConnectionState =
command.Connection.State;
if (((command.Connection.State
& global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
command.Connection.Open();
}
int returnValue;
try {
returnValue = command.ExecuteNonQuery();
}
finally {
if ((previousConnectionState ==
global::System.Data.ConnectionState.Closed)) {
command.Connection.Close();
}
}
return returnValue;
}
这段代码仔细阅读后发现很精巧,我们知道,打开连接操作时十分耗时的,如果我们要对数据库进行批量操作时,我们通过对这段代码特性的了解,可以首先自己打开链接,平批量操作结束时再自己关闭即可。
adapter.connection.open();
adapter.connection.close();
我们可以用stopwatch类来查看一下执行时间:
stopwatch sw=new stopwatch();
sw.start();
……
sw.stop();
messagebox.shoe(sw.elapsed.tostring());