简体   繁体   English

在ASP.NET中使用SQL事务更新数据

[英]Using an SQL Transaction in ASP.NET to Update Data

I'm attempting to update multiple tables using an SQL transaction. 我正在尝试使用SQL事务更新多个表。 Right now, the transaction is only affecting one of the tables ( dbo.Colors ). 现在,该事务仅影响其中一个表( dbo.Colors )。 However, the code is pretty much the same for all three, so I'm wondering where I'm running into an issue. 但是,这三个代码几乎相同,所以我想知道在哪里遇到问题。 The key difference between the tables is that one is getting information from asp:Textbox (es) while the other two are getting their data from drop down lists. 这些表之间的主要区别在于,一个是从asp:Textbox (es)获取信息,而另两个是从下拉列表中获取数据。 They are all related through a Session variable named "PlanID". 它们都通过一个名为“ PlanID”的会话变量关联。 Here is my code: 这是我的代码:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConversionConnect2"].ConnectionString);
    string query = "UPDATE dbo.Colors SET HeaderBackground = @HeaderBackground, HeaderText = @HeaderText, FooterBackground = @FooterBackground, FooterText = @FooterText,  ButtonText = @ButtonText, ButtonHover = @ButtonHover WHERE PlanID = @PlanID";
    string query2 = "UPDATE dbo.Fonts SET HeaderFont = @HeaderFont, FooterFont = @FooterFont, ButtonFont = @ButtonFont WHERE PlanID = @PlanID";
    string query3 = "UPDATE dbo.Sizes SET HeaderSize = @HeaderSize, FooterSize = @FooterSize, ButtonSize = @ButtonSize WHERE PlanID = @PlanID";

using (conn)
        {
            SqlTransaction trans = null;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();
                using (SqlCommand transCom = new SqlCommand(query, conn, trans))
                {
                    transCom.Parameters.AddWithValue("@PlanID", Session["planid"].ToString());
                    transCom.Parameters.AddWithValue("@HeaderBackground", txtheadercolor.Text);
                    transCom.Parameters.AddWithValue("@HeaderText", headertext.Text);
                    transCom.Parameters.AddWithValue("@FooterBackground", txtfootercolor.Text);
                    transCom.Parameters.AddWithValue("@FooterText", footertext.Text);
                    transCom.Parameters.AddWithValue("@ButtonText", txtbuttoncolor.Text);
                    transCom.Parameters.AddWithValue("@ButtonHover", txthovercolor.Text);
                    transCom.ExecuteNonQuery();
                }
                using (SqlCommand transCom2 = new SqlCommand(query2, conn, trans))
                {
                    transCom2.Parameters.AddWithValue("@PlanID", Session["planid"].ToString());
                    transCom2.Parameters.AddWithValue("@HeaderFont", headerfont.SelectedValue.ToString());
                    transCom2.Parameters.AddWithValue("@FooterFont", footerfont.SelectedValue.ToString());
                    transCom2.Parameters.AddWithValue("@ButtonFont", ddButtonFont.SelectedValue.ToString());
                    transCom2.ExecuteNonQuery();
                }
                using (SqlCommand transCom3 = new SqlCommand(query3, conn, trans))
                {
                    transCom3.Parameters.AddWithValue("@PlanID", Session["planid"].ToString());
                    transCom3.Parameters.AddWithValue("@HeaderSize", ddheadersize.SelectedValue);
                    transCom3.Parameters.AddWithValue("@FooterSize", ddfootersize.SelectedValue);
                    transCom3.Parameters.AddWithValue("@ButtonSize", ddButtonSize.SelectedValue);
                    transCom3.ExecuteNonQuery();
                }
                trans.Commit();
            }
            catch (Exception Ex)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
                else
                {
                    return;
                }
            }
            conn.Close();
        }

This code runs without errors, however, when I check dbo.Fonts and dbo.Sizes, I see that both tables were not updated. 这段代码运行没有错误,但是,当我检查dbo.Fonts和dbo.Sizes时,我看到两个表都没有更新。 Any suggestions? 有什么建议么?

Check this MSDN sample out. 检查此MSDN示例。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx

The .AddWithValue will try to do a type conversion. .AddWithValue将尝试进行类型转换。 It may or maynot be what you want. 它可能不是您想要的。

Here is a good debate on the subject. 这是一个很好的辩论。

http://forums.asp.net/t/1200255.aspx http://forums.asp.net/t/1200255.aspx

Also, string will be converted to nvarchar() which might have performance issues on the DBMS. 另外,字符串将被转换为nvarchar(),这可能在DBMS上有性能问题。 In short, use .Add and select the datatype if possible. 简而言之,使用.Add并选择数据类型(如果可能)。

Carve out a simple example like MSDN and test it first. 提出一个简单的示例,例如MSDN,然后对其进行测试。 Then modify it to your particular example. 然后将其修改为您的特定示例。

Without the actual table definition, more time, etc ... I can not give you an exact answer. 没有实际的表定义,更多的时间等,我无法给您确切的答案。

Good luck C# coding! 祝您好运C#编码!

... ...

I think you need another using clause for the transaction itself. 我认为您需要用于交易本身的另一个using子句。 Again, test with simple example then expand. 再次,用简单的示例进行测试,然后进行扩展。

Why use a using statement with a SqlTransaction? 为什么要在SqlTransaction中使用using语句?

    /* Code from Stack Overflow Answer */

using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"])) {
        cn.Open();
        using (SqlTransaction tr = cn.BeginTransaction()) {
            //some code
            tr.Commit();
        }
    }

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

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