关于多个SQL文执行时,回滚的问题

来源:百度知道 编辑:UC知道 时间:2024/09/23 13:17:14
如题,我写了如下代码,不知道能否执行
OleDbTransaction transaction;
transaction = conn.Connection.BeginTransaction();
string sqlString = "";
OleDbCommand oleDbCommand;
try
{
for(int i = 0; i< sqlList.Count; i++)
{
sqlString = sqlList[i].ToString();
oleDbCommand = new OleDbCommand(sqlString,
conn.Connection,
transaction);
}
transaction.Commit();
}
catch(Exception ex)
{
transaction.Rollback();
throw ex;
}
补充一下:
举例说明一下,如果执行到第3句SQL文时,出错,我希望第1,2句所执行的处理也被回滚,sjyh5201所说的应该是每执行一次,提交一次,这样每一句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);
}