首先至少要引用的檔案
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
(1)在需要執行sql業務中寫如下代碼:
ArrayList sqlList = new ArrayList();
string sqlStr1 = @"insert into....";
string sqlStr2 = @"update....";
sqlList.Add(sqlStr1 );
sqlList.Add(sqlStr2 );
if (sqlList.Count > 0)
{
var result= BatchExecuteNonQuery(sqlList); //事務操作
if (result)
{
//操作成功的代碼
}
else {
//操作失敗的代碼
}
}
(2)執行BatchExecuteNonQuery函數的代碼
public bool BatchExecuteNonQuery(ArrayList ALSql)
{
string strconntstring = WebConfigurationManager.ConnectionStrings["字元串"].ToString();
SqlConnection Conn = new SqlConnection(strconntstring);
if (Conn.State != ConnectionState.Open)
{
try
{
Conn.Open();
}
catch
{
throw new Exception("資料庫無法連接配接");
}
}
bool state= false;
SqlTransaction transaction = null;
if (Conn.State != ConnectionState.Open)
{
try
{
Conn.Open();
}
catch
{
throw new Exception("資料庫無法連接配接");
}
}
try
{
SqlCommand cmd = new SqlCommand();
transaction = Conn.BeginTransaction();
cmd.Transaction = transaction;
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
for (int i = 0; i < ALSql.Count; i++)
{
cmd.CommandText = ALSql[i].ToString();
cmd.ExecuteNonQuery();
}
transaction.Commit();
state= true;
}
catch (Exception ex)
{
state= false;
transaction.Rollback();
}
finally
{
Conn.Close();
}
return state;
}