1、創(chuàng)建事務(wù)的結(jié)構(gòu)
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供秦淮網(wǎng)站建設(shè)、秦淮做網(wǎng)站、秦淮網(wǎng)站設(shè)計、秦淮網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、秦淮企業(yè)網(wǎng)站模板建站服務(wù),10多年秦淮做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
SqlConnection sqlConnection = new SqlConnection();
...初始化連接
// 開啟事務(wù)
SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
// 將事務(wù)應(yīng)用于Command
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.Transaction = sqlTransaction;
try
{
// 利用sqlcommand進行數(shù)據(jù)操作
...
// 成功提交
sqlTransaction.Commit();
}
catch(Exception ex)
{
// 出錯回滾
sqlTransaction.Rollback();
}
2、簡單例子
{
DataTable dt = new DataTable();
System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection("連接字符串");
System.Data.SqlClient.SqlCommand cm = new System.Data.SqlClient.SqlCommand();
cm.Connection = cnn;
cnn.Open();
System.Data.SqlClient.SqlTransaction trans = cnn.BeginTransaction();
try
{
foreach(DataRow dr in dt.Rows)
{
cm.CommandText = "update [表] set [數(shù)量] = @amount where productID = @productID";
cm.Parameters.Add("@amount",SqlDbType.Int);
cm.Parameters["@amount"].Value = Convert.ToInt32(dr["amount"]);
cm.Parameters.Add("@productID",SqlDbType.VarChar);
cm.Parameters["@productID"].Value = dr["productID"].ToString();
cm.ExecuteNonQuery();
}
trans.Commit();
}
catch
{
trans.Rollback();
}
finally
{
cnn.Close();
trans.Dispose();
cnn.Dispose();
}
}
3、SQl server中的事務(wù)例子
begin transaction
save transaction A
insert into demo values('BB','B term')
rollback TRANSACTION A
create table demo2(name varchar(10),age int)
insert into demo2(name,age) values('lis',1)
rollback transaction
insert into demo values('BB','B term')
commit TRANSACTION A
commit TRANSACTION
4、注意
1。事務(wù)必須在連接打開后BeginTransaction();
2.事務(wù)添加到SqlCommand(sqlCommand.Transaction = sqlTransaction; )
3、其他數(shù)據(jù)庫對應(yīng)做相應(yīng)調(diào)整
4、可以用微軟提供的一個dll,很方便.