SQL语句的执行可以分为三种的方法进行批量执行。这里主要介绍使用事务机制批量执行语句。
这个函数是在windows service 上编写的。
public void InsertAll(List<string> SqlAll)
{
SqlConnection connetion=this.SqlConn(); //创建数据库连接
SqlTransaction transaction=null; //声明事务
SqlCommand command=null;
try{
connetion.Open(); //打开数据库连接
transaction=connetion.BeginTransaction(); //使用数据库连接创建事务
command=connetion.CreateCommand();
command.Transaction=transaction;
try{
for(int i=0;i<SqlAll.Count;i++)
{
if(!string.IsNullOrEmpty(SqlAll[i])) //判断当前SQL语句是否为空
{
command.CommandText=SqlAll[i];
command.ExecuteNonQuery();
}
}
transaction.Commit(); //事务提交
}
catch(Exception ex)
{
transaction.Rollback(); //事务撤销
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
connetion.Close();
}
}
catch(Exception ee)
{
System.Diagnostics.Debug.WriteLine(ee.Message);
}
}
通过事务机制保证批量的数据能够正确执行,如果任何一个SQL执行错误就会撤销本次事务,通过事务SQL语句的批量执行主要通过的SQLCOMMAND来完成,这避免了数据库连接的不断打开和关闭操作,执行效率比较高。