/// 执行多条SQL语句,事务处理
///
/// 以";"相隔的查询语句
public bool InsertMoreDB(string strSQL){
char[] de={’;’};
string strChildSQL;
int i;
string[] strSQLArr=strSQL.Split(de);
bool IsControll=true;
SqlConnection conn=DBCreateCN();
SqlCommand myCommand=new SqlCommand();
SqlTransaction myTrans;
myTrans=conn.BeginTransaction();
myCommand.Connection = conn;
myCommand.Transaction = myTrans;
try
{
for(i=0;i
{
strChildSQL=strSQLArr[i];
myCommand.CommandText =strChildSQL;
myCommand.ExecuteNonQuery();
}
myTrans.Commit();
IsControll=true;
}
catch(Exception)
{
try
{
IsControll=false;
myTrans.Rollback();
}
catch (SqlException)
{
// Handle possible exception here
}
}
finally
{
conn.Close();
}
return IsControll;
}
本文介绍了一种在C#中执行多条SQL语句的方法,并通过事务来确保操作的原子性和一致性。该方法首先将SQL语句按分号分割成多个子语句,然后逐一执行每个子语句。如果所有子语句都能成功执行,则提交事务;若执行过程中出现异常,则回滚事务以撤销已做的更改。
480

被折叠的 条评论
为什么被折叠?



