我有兩個插入語句插入數據庫中的記錄。我已經使用了事務範圍,以便在任何語句失敗的情況下,沒有任何記錄被更新。在第二個過程中,插入失敗,但它將數據庫中的記錄插入到第一個語句中。我在代碼中缺少什麼?交易範圍c#
連接字符串
<add name="Transac.Properties.Settings.TransacDbConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=Transac;Integrated Security=True" providerName="System.Data.SqlClient" />
private void button1_Click(object sender, EventArgs e) {
var scopeOptions = new TransactionOptions();
scopeOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
scopeOptions.Timeout = TimeSpan.MaxValue;
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required,scopeOptions)) {
try {
cmd = new SqlCommand("SalesSave", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@BillNo", lblBillNo.Text));
cmd.Parameters.Add(new SqlParameter("@CustName", cboCust_Name.Text.ToUpper()));
cmd.Parameters.Add(new SqlParameter("@Mobile", txtMob.Text));
cmd.ExecuteNonQuery();
cmd = new SqlCommand("SubSave", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SubBillNo", lblBillNo.Text));
cmd.Parameters.Add(new SqlParameter("@ItemName", dataGridView1.Rows[i].Cells[0].Value.ToString().ToUpper()));
cmd.Parameters.Add(new SqlParameter("@Qty", dataGridView1.Rows[i].Cells[1].Value.ToString()));
//cmd.Parameters.Add(new SqlParameter("@Price", dataGridView1.Rows[i].Cells[2].Value.ToString()));
cmd.ExecuteNonQuery();
transactionScope.Complete();
transactionScope.Dispose();
}
catch (Exception e1) {
MessageBox.Show(e1.Message);
}
}
}
存儲過程1:
ALTER PROCEDURE [dbo].[SalesSave]
(
@SalesBillNo as varchar(50),
@CustName as varchar(50),
@Mobile as nvarchar(50)
)
AS
begin
insert into Sales(
SalesBillno,
CustName,
Mobile
)
values (
@SalesBillNo,
@CustName,
@Mobile
)
end
存儲過程2
ALTER PROCEDURE [dbo].[SubSave]
@SubSalesBillNo as varchar(50),
@ItemName as nvarchar(50),
@Qty as money,
@Price as money
AS
begin
INSERT INTO SubSales
VALUES(
@SubSalesBillNo,
@ItemName,
@Qty,
@Price
)
end
您的消息框是否顯示第二個存儲過程中的異常? 爲什麼當你有一個Using塊時調用dispose? – Adam47
是的,它顯示第二個存儲過程中的異常,因爲我已經明確地評論了一個參數,所以它會拋出錯誤,事務將回滾但不是。之前我使用的是交易聲明,這就是爲什麼處置在那裏我會刪除它 – NoviceToProgramming
真正的問題是:根本使用3個交易的目的是什麼?另外:只有一個命令使用轉換的目的是什麼? –