C# 对多个方法C使用单个事务?
假设我有一个Insert按钮,其中有多个方法,它们在数据库中读取、插入和更新等。是否可以对所有这些被调用的方法使用单个事务如:C# 对多个方法C使用单个事务?,c#,ms-access,C#,Ms Access,假设我有一个Insert按钮,其中有多个方法,它们在数据库中读取、插入和更新等。是否可以对所有这些被调用的方法使用单个事务如: private void method_A(){/* doing tons of db stuff.. */} private void method_B(){/*..*/} private void method_C(){/*..*/} protected void Insert_OnClick(object sender, EventArgs e) {
private void method_A(){/* doing tons of db stuff.. */}
private void method_B(){/*..*/}
private void method_C(){/*..*/}
protected void Insert_OnClick(object sender, EventArgs e)
{
//begin transaction
Method_A();
Method_B();
Method_C();
//end transaction
}
这条路可行吗?以前从未使用过事务。
顺便说一句,如果有必要,请使用MS Access db
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand();
OleDbTransaction transaction = null;
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the transaction.
try
{
connection.Open();
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
// Assign transaction object for a pending local transaction.
command.Connection = connection;
command.Transaction = transaction;
Method1(command.connection);
Method2(command.connection);
}
}
像这样的
因此,您需要使用一个连接,然后设置事务级别并运行您的方法
更多信息请参见此处:您看到了吗?@PaulF它没有显示如何通过C#实现事务,或者如果我简单地添加
begintransaction
,它会工作吗。。C#代码和方法<代码>提交[事务|工作]回滚[事务|工作]?将方法1()代码>和Method2()代码>现在在事务中,还是我必须传递参数中的任何内容?@Nyprez我相信您必须通过连接。但是事务应该保留下来,我想@Andrew Kilburn是命令
还是连接
,我应该传递给Method1()代码>和Method2()代码>?@您需要传递连接,但如果您想一次执行所有命令,您可以将命令变量传入您的方法并返回它。@Nyprez进行得如何?