首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接与SqlTransaction是关闭错误

连接与SqlTransaction是关闭错误
EN

Stack Overflow用户
提问于 2013-08-12 14:59:31
回答 1查看 2.3K关注 0票数 0

我有一个测试SQL Server表,其数据如下

代码语言:javascript
复制
  ItemId    Description ItemCost
    1           first item  100
    2           second item 200
    3           third item  300

以及将项添加到Items表中的存储过程。

代码语言:javascript
复制
create proc spInsertItem
 @itemId int
,@itemDescription varchar(50)
,@itemCost decimal
as
begin
    if(@itemCost < 0)
        begin
            raiserror('cost cannot be less than 0',16,1)
        end
    else
        begin
            begin try
                begin tran
                    insert into Items(itemid, [description],itemCost)
                    values (@itemid, @itemdescription,@itemCost)
                commit tran
            end try
        begin catch
            rollback tran
                select   ERROR_LINE()as errorLine
                        ,ERROR_MESSAGE() as errorMessage
                        ,ERROR_STATE() as errorState
                        ,ERROR_PROCEDURE() as errorProcedure
                        ,ERROR_NUMBER() as errorNumber
        end catch
    end
end 

当我在SSMS中执行该过程时,它会正确地报告负成本的错误。当我使用以下代码时:

代码语言:javascript
复制
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcsI3"].ConnectionString;
            using (var con = new SqlConnection(cs))
            {
                SqlTransaction tran = con.BeginTransaction();
                try
                {
                    using (var cmd = new SqlCommand("spInsertItem", con))
                    {

                        con.Open();
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@itemId", Convert.ToInt32(txtItemId.Text));
                        cmd.Parameters.AddWithValue("@itemdescription", txtItemDescription.Text);
                        cmd.Parameters.AddWithValue("@itemCost", Convert.ToInt32(txtItemCost.Text));
                        cmd.ExecuteNonQuery();
                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message; //the intent is to print the error message to the user 
                    tran.Rollback();
                }
            }
        }

当我使用这段代码时,我会得到一个异常,即连接已关闭,但随后我跳到SSMS,发现它正常工作。在我把东西搬到杂乱无章地工作之前,我想知道为什么我会收到连接被关闭的错误。每当我将可行的数据输入到该表中时,该过程也会起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-12 15:04:46

尝试在BeginTransaction之前打开连接

代码语言:javascript
复制
using (var con = new SqlConnection(cs))
{
   con.Open();
   SqlTransaction tran = con.BeginTransaction(); 
   // rest of the code 
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18190340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档