同时执行两条SQL语句的方法:
public static void ExecuteSqlTran(string SQLString1,string SQLString2)
{
using (SqlConnection conn = new SqlConnection(strDBConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection=conn;
SqlTransaction tx=conn.BeginTransaction();
cmd.Transaction=tx;
try
{
cmd.CommandText=SQLString1;
cmd.ExecuteNonQuery();
cmd.CommandText=SQLString2;
cmd.ExecuteNonQuery();
tx.Commit();
}
catch(System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
如果有多条SQL语句需要放在一个事务里实现执行,就用下面这个方法:
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection=conn;
SqlTransaction tx=conn.BeginTransaction();
cmd.Transaction=tx;
try
{
for(int n=0;n<SQLStringList.Count;n++)
{
string strsql=SQLStringList[n].ToString();
if (strsql.Trim().Length>1)
{
cmd.CommandText=strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch(System.Data.SqlClient.SqlException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
方法虽然简单,但确实省了不少时间:)
(作者:李天平 转载请注明)