下面就將為您介紹如何使用事務(wù)一次處理多條SQL語句的方法,包括SQL中事務(wù)的寫法以及調(diào)用的方法供您參考,希望對(duì)您學(xué)習(xí)SQL語句的執(zhí)行能夠有所幫助。
執(zhí)行一個(gè)操作時(shí),要同時(shí)修改多張表里的數(shù)據(jù),并且每條數(shù)據(jù)都必須操作成功,才算執(zhí)行成功,為了防止有些數(shù)據(jù)操作失敗,有些成功,而造成的數(shù)據(jù)錯(cuò)亂,我們要使用事務(wù)。
事務(wù)就是:只有所有操作都成功則成功,只要有一條數(shù)據(jù)操作失敗,則回滾。
后臺(tái)寫事務(wù):
/// <summary>
/// 執(zhí)行多條SQL語句,實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)。
/// </summary> access數(shù)據(jù)庫(kù)
/// <param name="SQLStringList">多條SQL語句</param>
public static void ExecuteSqlTran(List<string> SQLStringList)
{
using (OleDbConnection conn = new OleDbConnection(SqlHelper.ConString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbTransaction 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.OleDb.OleDbException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
/// <summary>
/// 執(zhí)行多條SQL語句,實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)。
/// </summary>sql2000數(shù)據(jù)庫(kù)
/// <param name="SQLStringList">多條SQL語句</param>
public static void ExecuteSqlTran(List<string> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(SqlHelper.ConString))
{
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);
}
}
}
前臺(tái)調(diào)用:
try
{
//1.查出會(huì)員余額
decimal usermoney = SqlDal.EntityUserinfo.GetModel(int.Parse(cookieUserID)).Money;
//2.修改余額
decimal Zmoney = usermoney + moAD.Commission;
//寫SQL語句
List<string> SQLStringList = new List<string>();
string clickSql = "insert into [user] (name,age)values('" + 小名 + "','“+4歲+”')";
string userSql = "update [class] set [name]='" + 幼兒園 + "' where id=" + 2 + " ";
SQLStringList.Add(clickSql);
SQLStringList.Add(userSql);
SqlDal.SqlHelper.ExecuteSqlTran(SQLStringList);
//數(shù)據(jù)庫(kù)操作成功
//提示
CommonClass.Xmls xmls1 = new CommonClass.Xmls();
string path1 = CommonClass.Unit.GetMapPath(@"/Admin/Configs/SysSettingInfo.config");
string ClickTishi = xmls1.GetXmlNode(path1, "SysSettingInfo/ClickTishi");
//替換字符
ClickTishi = ClickTishi.Replace("[$]", moAD.Commission.ToString("0.00"));
context.Response.Write(ClickTishi); //輸出
}
catch (Exception ex)
{
//Response.Write(ex.Message);
context.Response.Write("操作失?。? + ex.Message); //輸出
}