如何使用C#的SqlTransaction [英] how to use sqltransaction in c#

查看:501
本文介绍了如何使用C#的SqlTransaction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码同时执行两个指令。我用的SqlTransaction保证要么所有的命令得到执行或回滚back.When我运行我的程序没有交易,它运行正常,但是当我用交易与他们,他们表现出的错误。我的代码如下;

I am using following code to execute two commands at once. I used sqltransaction to assure either all command get executed or rolled back.When I run my program without "transaction" it run properly but when I use "transaction" with them they show error. My code is as follow;

SqlTransaction transaction = connectionsql.BeginTransaction();

try
{
    SqlCommand cmd1 = new SqlCommand("select account_name from master_account where NOT account_name = 'BANK' AND NOT account_name = 'LOAN'", connectionsql);
    SqlDataReader dr1 = cmd1.ExecuteReader();
    while (dr1.Read())
    {
        comboBox1.Items.Add(dr1[0].ToString().Trim());
    }
    cmd1.Dispose();
    dr1.Dispose();

    SqlCommand cmd2 = new SqlCommand("select items from rate",connectionsql);
    SqlDataReader dr2 = cmd2.ExecuteReader();
    while (dr2.Read())
    {
        comboBox2.Items.Add(dr2[0].ToString().Trim());
    }
    cmd2.Dispose();
    dr2.Dispose();
    transaction.Commit();

    dateTimePicker4.Value = dateTimePicker3.Value;
}
catch(Exception ex)
{
    transaction.Rollback();
    MessageBox.Show(ex.ToString());
}

和错误:

推荐答案

您必须告诉你的SqlCommand对象使用的事务:

You have to tell your SQLCommand objects to use the transaction:

cmd1.Transaction = transaction;

或在构造函数中:

SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);

确认有connectionsql对象开放了。

Make sure to have the connectionsql object open, too.

但是,所有你正在做的是SELECT语句。当你使用INSERT,UPDATE,等输入操作的交易将获益更多。

But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.

这篇关于如何使用C#的SqlTransaction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆