简体   繁体   English

如何在C#中将DataAdapter与SqlTransaction一起使用?

[英]How to use DataAdapter with SqlTransaction in C#?

I need to create 2 buttons, one for starting a transaction ( startButton ) and one for committing a transaction ( commitButton ). 我需要创建2个按钮,一个用于启动事务( startButton ),一个用于提交事务( commitButton )。

I got stuck trying to implement it for the SELECT command. 我陷入尝试为SELECT命令实现它的过程。

When I press the commitButton I get the error that the transaction has already completed and is no longer usable. 当我按下commitButton我收到错误消息,表明事务已完成并且不再可用。

public void startTransaction(IsolationLevel isolationLevel) {
    connectSQL();
    connection.Open();
    transaction = connection.BeginTransaction(isolationLevel);
    Console.WriteLine("Transaction started !");
}

public void commitTransaction() {
    this.transaction.Commit();
    connection.Close();
    Console.WriteLine("Transaction commited !");
}

public DataTable readAllRezervari() {
    try {
        String selectSql = "SELECT * FROM Rezervari;";
        SqlCommand sqlCommand = new SqlCommand(selectSql, connection, transaction);
        rezervariDataAdapter.SelectCommand = sqlCommand;
        rezervariDataAdapter.Fill(rezervariDataSet, "Rezervari");
    }
    catch (Exception e) {
        Console.WriteLine("ERROR: " + e);
        try {
            transaction.Rollback();
        }
        catch (Exception e2) {
            Console.WriteLine("ERROR: " + e2);
        }
    }
    finally {
        connection.Close();
    }
    rezervariDataTable = rezervariDataSet.Tables["Rezervari"];
    return rezervariDataTable;
}
using (SqlConnection cn = new SqlConnection(ConnectionString.GetConnection()))         
{             
    cn.Open();
    SqlTransaction transction = cn.BeginTransaction();
    SqlDataAdapter sda= new SqlDataAdapter("Select * From TableName", cn);
    sda.SelectCommand.Transaction = transction; 
    sda.Fill(ds, "TableName");
    transction.Commit();                 
}

It appears you are trying to use Transaction Commit and Rollback as a way for the user to commit or rollback their changes. 看来您正在尝试使用事务提交和回滚作为用户提交或回滚其更改的方式。 I always believed it was incase there was an issue with the code or the data you could prevent multiple changes from being partially commited resulting in bad data. 我一直认为这是在代码或数据出现问题的情况下,您可以防止部分提交多个更改而导致数据损坏的情况。 I really know more vb.net than c# so forgive me if my format is off. 我真的比v#.c了解更多vb.net,所以请原谅我的格式关闭。

Here is a thought:commit all their data to a datatable and store it in a session variable or view state 这是一个想法:将其所有数据提交到数据表中并将其存储在会话变量或视图状态中

something like 就像是

 rezervariDataTable  = session("reservari");

if the user hits commit button: It does the code to write the transaction to the database. 如果用户单击提交按钮:它执行代码以将事务写入数据库。

If the user hits rollback: 如果用户点击回滚:

     reservariDataTable = Nothing;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM