假设我有一个Insert-button,我在其中有多个方法,在数据库中读取,插入和更新等。是否可以对所有这些被调用的方法使用单个事务?的像:
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数据库。
答案 0 :(得分:1)
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);
}
}
那样的东西?
所以你使用一个连接,然后设置事务级别并运行你的方法。
有关详细信息,请参阅此处:https://msdn.microsoft.com/en-us/library/93ehy0z8(v=vs.110).aspx