事务应用-运行多条SQL语句
时间:2022-03-13 22:58
#region ExtensionMethod
/// <summary>
/// 依据学号来给指定的学生加分-陈方林-2014年3月22日15:17:59
/// </summary>
/// <param name="strStudentNoScore">用来加分的sql语句</param>
/// <returns>返回运行的结果</returns>
public bool TeaGiveScores(string[] strStudentNoScore) {
//打开数据库连接
sqlcon.Open();
//声明sql事务
SqlTransaction myTrans;
//sql命令对象
SqlCommand mycmd = new SqlCommand();
//声明命令对象的连接数据库
mycmd.Connection = sqlcon;
//开启事务
myTrans = sqlcon.BeginTransaction();
//设置将在命令对象中运行的事务
mycmd.Transaction = myTrans;
try
{
//遍历字符串数组中的sql语句
for (int i = 0; i < strStudentNoScore.Length; i++)
{
mycmd.CommandText = strStudentNoScore[i];
int r =mycmd.ExecuteNonQuery();
}
//事务提交
myTrans.Commit();
return true;
}
catch (Exception)
{
//运行错误,事务回滚
if (myTrans != null)
myTrans.Rollback();
return false;
}
finally
{
//关闭连接
if (sqlcon != null)
sqlcon.Close();
}
}
#endregion ExtensionMethod
总结
事务操作大致有(温故)
BeginTrans:開始事务
CommitTrans:提交事务
RollBackTrans:回滚事务
主要是对于数据处理的一个好的封装,作为处理的单元。结合sql经常使用的几个对象,来处理多行sql语句。