Using datareaders with sqltransactions

你。 提交于 2020-02-02 12:59:47

问题


I am using SqlTransactions in my code for roll back purpose. Within the transaction I got multiple statements to be executed with may include selects inserts and updates. All these statements are within the scope of the sqltransaction. Everything works fine just for one problem. I am using datareaders for select statements . And these readers are closed once they are used. This forces the connection to be lost and every thing fails. Does any one have a solution on whether I can use datareaders within a sqltransaction??


回答1:


A DataReader will only close the connection if the CommandBehavior.CloseConnection option was set when calling ExecuteReader.

You should be OK if you avoid setting this option.




回答2:


You should open the SqlConnection by itself.
The SqlDataReader doesn't close the SqlConnection when you close the DataReader

For example:

using(SqlConnection cn = GetConnection())
{
    cn.Open();
    SqlTransaction tr = cn.BeginTransaction("myTransaction");
    .....

    SqlCommand command = new SqlCommand(sqlString, cn);

    using(SqlDataReader reader = command.ExecuteReader())
    {
        .....
    }

    SqlCommand command1 = new SqlCommand(sqlString1, cn);
    using(SqlDataReader reader1 = command1.ExecuteReader())
    {
        .....
    }
    tr.Commit();
}


来源:https://stackoverflow.com/questions/11453373/using-datareaders-with-sqltransactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!