教您用事務一次處理多條SQL語句
下面就將為您介紹如何使用事務一次處理多條SQL語句的方法,包括SQL中事務的寫法以及調用的方法供您參考,希望對您學習SQL語句的執行能夠有所幫助。
執行一個操作時,要同時修改多張表里的數據,并且每條數據都必須操作成功,才算執行成功,為了防止有些數據操作失敗,有些成功,而造成的數據錯亂,我們要使用事務。
事務就是:只有所有操作都成功則成功,只要有一條數據操作失敗,則回滾。
后臺寫事務:
/// <summary>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary> access數據庫
/// <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>
/// 執行多條SQL語句,實現數據庫事務。
/// </summary>sql2000數據庫
/// <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);
}
}
}
前臺調用:
try
{
//1.查出會員余額
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);
//數據庫操作成功
//提示
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); //輸出
}
【編輯推薦】