【问题标题】:SqlCommand SQL statement being executed twiceSqlCommand SQL 语句被执行两次
【发布时间】:2023-03-12 19:07:01
【问题描述】:

我正在使用 C# 创建一个 ASP.NET 应用程序,每次尝试使用 SqlCommand 执行 SQL INSERT 时,该命令都会执行两次。我实现了这篇文章 (SQL Insert query is executed twice) 中的内容,但仍然没有帮助。

代码如下:

protected void btn_Add_Click(object sender, EventArgs e)
{
        error.InnerHtml = " ";

        SqlConnection MyConn = new SqlConnection("Data Source=.\\SQLEXPRESS;"
            + "Initial Catalog=SIMON;"
            + "Persist Security Info=True;"
            + "User ID=username;Password=password");

        string sqlStatement = @"INSERT INTO [Network_Equipment] "
            + "([Network_Equipment_Name], [Network_Equipment_Type_ID], [IP_Address], [FQDN], [NetBIOS_Name], [Building_ID], [Description])"
            + " VALUES "
            + "(@Network_Equipment_Name, @Network_Equipment_Type_ID, @IP_Address, @FQDN, @NetBIOS_Name, @Building_ID, @Description)";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, MyConn);
            sqlCmd.Connection = MyConn;

            sqlCmd.Parameters.AddWithValue("@Network_Equipment_Name", ((in_Add_Equipment.Value == null) ? (object)DBNull.Value : (object)in_Add_Equipment.Value));
            sqlCmd.Parameters.AddWithValue("@Network_Equipment_Type_ID", ((ddl_Equipment_Type.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Equipment_Type.SelectedValue));
            sqlCmd.Parameters.AddWithValue("@IP_Address", ((in_IP_Address.Value == null) ? (object)DBNull.Value : (object)in_IP_Address.Value));
            sqlCmd.Parameters.AddWithValue("@FQDN", ((in_FQDN.Value == null) ? (object)DBNull.Value : (object)in_FQDN.Value));
            sqlCmd.Parameters.AddWithValue("@NetBIOS_Name", ((in_NetBIOS.Value == null) ? (object)DBNull.Value : (object)in_NetBIOS.Value));
            sqlCmd.Parameters.AddWithValue("@Building_ID", ((ddl_Building.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Building.SelectedValue));
            sqlCmd.Parameters.AddWithValue("@Description", ((ta_Description.Value == null) ? (object)DBNull.Value : (object)ta_Description.Value));


            try
            {
                MyConn.Open();
            }
            catch (Exception er)
            {
                error.InnerHtml = er.ToString();
                return;
            }

            try
            {
                sqlCmd.ExecuteNonQuery();
            }
            catch (Exception er)
            {
                error.InnerHtml = er.ToString();
                return;
            }

            error.InnerHtml = "Successfully added: " + in_Add_Equipment.Value;

            sqlCmd.Dispose();
            sqlCmd = null;
            MyConn.Close();

            in_Add_Equipment.Value = "";
            ddl_Equipment_Type.SelectedIndex = 0;
            in_IP_Address.Value = "";
            in_FQDN.Value = "";
            in_NetBIOS.Value = "";
            ddl_Building.SelectedIndex = 0;
            ta_Description.Value = "";

            GridView1.DataBind();
}

我已经在调试模式下运行了它,并且 sqlCmd.ExecuteNonQuery() 只调用了一次,但我添加了两个相同的条目。

我错过了什么和/或做错了什么?

-------- 编辑--------

我使用了john ryan代码的修改版,但还是加了两次。

以下是与此相关的所有代码:

设备.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Equipment.aspx.cs" Inherits="SIMON.Equipment" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        // disables the button specified and sets its style to a disabled "look".
        function disableButtonOnClick(oButton, sButtonText, sCssClass) {
            oButton.disabled = true; // set button to disabled so you can't click on it.
            oButton.value = sButtonText; // change the text of the button.
            oButton.setAttribute('className', sCssClass); // IE uses className for the css property.
            oButton.setAttribute('class', sCssClass); // Firefox, Safari use class for the css property. (doesn't hurt to do both).
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                <div id="error" runat="server">&nbsp;</div>
                <div>
                    <fieldset style="display: inline-block; padding: 5px; -moz-border-radius: 8px; border-radius: 8px;">
                    <legend style="text-decoration: underline;">[ Add Equipment ]</legend>
                        <table cellpadding="3px" style="border: 0px; width: 300px;">
                            <tbody>
                                <tr>
                                    <td style="text-align: left;"><label for="in_Add_Equipment" style="white-space: nowrap;">Equipment Name</label></td>
                                    <td style="text-align: right;"><input id="in_Add_Equipment" runat="server" size="20" /></td>
                                    <td style="text-align: left;"><label for="ddl_Equipment_Type" style="white-space: nowrap;">Equipment Type</label></td>
                                    <td style="text-align: right;">
                                        <asp:DropDownList ID="ddl_Equipment_Type" 
                                            runat="server" DataSourceID="Network_Equipment_Type" DataTextField="Network_Equipment_Type" 
                                            DataValueField="Network_Equipment_Type_ID"></asp:DropDownList>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="text-align: left;"><label for="in_IP_Address" style="white-space: nowrap;">IP Address</label></td>
                                    <td style="text-align: right;"><input id="in_IP_Address" runat="server" size="20" class="OnlyNumeric" /></td>
                                    <td style="text-align: left;"><label for="in_FQDN" title="Fully Qualified Domain Name" style="white-space: nowrap;">FQDN</label></td>
                                    <td style="text-align: right;"><input id="in_FQDN" runat="server" size="20" /></td>
                                </tr>
                                <tr>
                                    <td style="text-align: left;"><label for="in_NetBIOS" style="white-space: nowrap;">NetBIOS Name</label></td>
                                    <td style="text-align: right;"><input id="in_NetBIOS" runat="server" size="20" /></td>
                                    <td style="text-align: left;"><label for="ddl_Building" style="white-space: nowrap;">Building</label></td>
                                    <td style="text-align: right;">
                                        <asp:DropDownList ID="ddl_Building" runat="server" 
                                            DataSourceID="Buildings" DataTextField="Building_Name" 
                                            DataValueField="Building_ID"></asp:DropDownList>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="text-align: left;"><label for="ta_Description" style="white-space: nowrap;">Description</label></td>
                                    <td style="text-align: right;" colspan="3"><textarea id="ta_Description" runat="server" cols="50" rows="3"></textarea></td>
                                </tr>
                                <tr>
                                    <td colspan="4" style="text-align: right;">
                                        <asp:Button ID="btn_Add" Text="Add" CssClass="ui-state-default ui-corner-all" runat="server" OnClick="btn_Add_Click" />
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </fieldset>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <p></p>
        <fieldset style="display: inline-block; padding: 5px; -moz-border-radius: 8px; border-radius: 8px;">
        <legend style="text-decoration: underline;">[ Update Equipment ]</legend>
           <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:SIMON-Writer %>" 
                        DeleteCommand="DELETE FROM [Network_Equipment] WHERE [Network_Equipment_ID] = @original_Network_Equipment_ID" 
                        OldValuesParameterFormatString="original_{0}" 
                        SelectCommand="SELECT * FROM [All_Network_Equipment-Simplified]" 

                        UpdateCommand="UPDATE [Network_Equipment] SET [Network_Equipment_Name] = @Network_Equipment_Name, [Network_Equipment_Type_ID] = @Network_Equipment_Type_ID, [IP_Address] = @IP_Address, [FQDN] = @FQDN, [NetBIOS_Name] = @NetBIOS_Name, [Building_ID] = @Building_ID, [Description] = @Description, [Active] = @Active WHERE [Network_Equipment_ID] = @original_Network_Equipment_ID">
                        <DeleteParameters>
                            <asp:Parameter Name="original_Network_Equipment_ID" Type="Int32" />
                        </DeleteParameters>
                        <InsertParameters>
                            <asp:Parameter Name="Network_Equipment_Name" Type="String" />
                            <asp:Parameter Name="Network_Equipment_Type_ID" Type="Int32" />
                            <asp:Parameter Name="IP_Address" Type="String" />
                            <asp:Parameter Name="FQDN" Type="String" />
                            <asp:Parameter Name="NetBIOS_Name" Type="String" />
                            <asp:Parameter Name="Building_ID" Type="Int32" />
                            <asp:Parameter Name="Description" Type="String" />
                            <asp:Parameter Name="Active" Type="Boolean" />
                        </InsertParameters>
                        <UpdateParameters>
                            <asp:Parameter Name="Network_Equipment_Name" Type="String" />
                            <asp:Parameter Name="Network_Equipment_Type_ID" Type="Int32" />
                            <asp:Parameter Name="IP_Address" Type="String" />
                            <asp:Parameter Name="FQDN" Type="String" />
                            <asp:Parameter Name="NetBIOS_Name" Type="String" />
                            <asp:Parameter Name="Building_ID" Type="Int32" />
                            <asp:Parameter Name="Description" Type="String" />
                            <asp:Parameter Name="Active" Type="Boolean" />
                            <asp:Parameter Name="original_Network_Equipment_ID" Type="Int32" />
                        </UpdateParameters>
                    </asp:SqlDataSource>
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                        CellPadding="4" DataKeyNames="Network_Equipment_ID" 
                        DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField DataField="Network_Equipment_ID" 
                                HeaderText="Network_Equipment_ID" ReadOnly="True" 
                                SortExpression="Network_Equipment_ID" Visible="False" />
                            <asp:BoundField DataField="Network_Equipment_Name" HeaderText="Equipment Name" SortExpression="Network_Equipment_Name" />
                            <asp:BoundField DataField="Network_Equipment_Type_ID" HeaderText="Network_Equipment_Type_ID" SortExpression="Network_Equipment_Type_ID" Visible="False" />
                            <asp:TemplateField HeaderText="Equipment Type" SortExpression="Network_Equipment_Type">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="DropDownList1" runat="server" 
                                        DataSourceID="Network_Equipment_Type" DataTextField="Network_Equipment_Type" 
                                        DataValueField="Network_Equipment_Type_ID" 
                                        SelectedValue='<%# Bind("Network_Equipment_Type_ID") %>'>
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Network_Equipment_Type") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="IP_Address" HeaderText="IP Address" SortExpression="IP_Address" />
                            <asp:BoundField DataField="FQDN" HeaderText="FQDN" SortExpression="FQDN" />
                            <asp:BoundField DataField="NetBIOS_Name" HeaderText="NetBIOS Name" SortExpression="NetBIOS_Name" />
                            <asp:BoundField DataField="Building_ID" HeaderText="Building_ID" SortExpression="Building_ID" Visible="False" />
                            <asp:TemplateField HeaderText="Building" SortExpression="Building_Name">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="Buildings" 
                                        DataTextField="Building_Name" DataValueField="Building_ID" 
                                        SelectedValue='<%# Bind("Building_ID") %>'>
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Building_Name") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description" SortExpression="Description">
                                <EditItemTemplate>
                                    <asp:TextBox ID="TextBox3" runat="server" Height="50px" Text='<%# Bind("Description") %>' TextMode="MultiLine" Width="200px"></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:CheckBoxField DataField="Active" HeaderText="Active" SortExpression="Active" />
                            <asp:CommandField ShowEditButton="True" />
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    </asp:GridView>
                    <br />
                    <asp:SqlDataSource ID="Network_Equipment_Type" runat="server" ConnectionString="<%$ ConnectionStrings:SIMON-Reader %>" 
                        SelectCommand="SELECT DISTINCT * FROM [Network_Equipment_Types] ORDER BY [Network_Equipment_Type]">
                    </asp:SqlDataSource>
                    <asp:SqlDataSource ID="Buildings" runat="server" ConnectionString="<%$ ConnectionStrings:SIMON-Reader %>" 
                        SelectCommand="SELECT DISTINCT * FROM [Buildings] ORDER BY [Building_Name]">
                    </asp:SqlDataSource>
                </ContentTemplate>
            </asp:UpdatePanel>
        </fieldset>
    </div>
    </form>
</body>
</html>

设备.aspx.cs

namespace SIMON
{
    public partial class Equipment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PostBackOptions optionsSubmit = new PostBackOptions(btn_Add);
                btn_Add.OnClientClick = "disableButtonOnClick(this, 'Please wait...', 'disabled_button ui-corner-all'); ";
                btn_Add.OnClientClick += ClientScript.GetPostBackEventReference(optionsSubmit);
            }
        }

        protected void btn_Add_Click(object sender, EventArgs e)
        {
            error.InnerHtml = "&nbsp;";

            SqlTransaction trans = null;
            using (SqlConnection MyConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SIMON-Writer"].ToString()))
            {

                MyConn.Open();
                trans = MyConn.BeginTransaction();

                string sqlStatement = "INSERT INTO [Network_Equipment] "
                    + "([Network_Equipment_Name], [Network_Equipment_Type_ID], [IP_Address], [FQDN], [NetBIOS_Name], [Building_ID], [Description])"
                    + " VALUES "
                    + "(@Network_Equipment_Name, @Network_Equipment_Type_ID, @IP_Address, @FQDN, @NetBIOS_Name, @Building_ID, @Description)";

                using (SqlCommand sqlCmd = new SqlCommand(sqlStatement, MyConn))
                {

                    sqlCmd.Transaction = trans;
                    sqlCmd.Connection = MyConn;

                    sqlCmd.Parameters.AddWithValue("@Network_Equipment_Name", ((in_Add_Equipment.Value == null) ? (object)DBNull.Value : (object)in_Add_Equipment.Value));
                    sqlCmd.Parameters.AddWithValue("@Network_Equipment_Type_ID", ((ddl_Equipment_Type.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Equipment_Type.SelectedValue));
                    sqlCmd.Parameters.AddWithValue("@IP_Address", ((in_IP_Address.Value == null) ? (object)DBNull.Value : (object)in_IP_Address.Value));
                    sqlCmd.Parameters.AddWithValue("@FQDN", ((in_FQDN.Value == null) ? (object)DBNull.Value : (object)in_FQDN.Value));
                    sqlCmd.Parameters.AddWithValue("@NetBIOS_Name", ((in_NetBIOS.Value == null) ? (object)DBNull.Value : (object)in_NetBIOS.Value));
                    sqlCmd.Parameters.AddWithValue("@Building_ID", ((ddl_Building.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Building.SelectedValue));
                    sqlCmd.Parameters.AddWithValue("@Description", ((ta_Description.Value == null) ? (object)DBNull.Value : (object)ta_Description.Value));


                    try
                    {
                        sqlCmd.ExecuteNonQuery();
                        trans.Commit();
                    }
                    catch (Exception er)
                    {
                        error.InnerHtml = er.ToString();
                        return;
                    }
                    finally
                    {
                        MyConn.Close();

                        error.InnerHtml = "Successfully added: " + in_Add_Equipment.Value;

                        in_Add_Equipment.Value = "";
                        ddl_Equipment_Type.SelectedIndex = 0;
                        in_IP_Address.Value = "";
                        in_FQDN.Value = "";
                        in_NetBIOS.Value = "";
                        ddl_Building.SelectedIndex = 0;
                        ta_Description.Value = "";

                        GridView1.DataBind();
                    }
                }
            }
        }
    }
}

-------- 编辑 2 --------

我已经找到了导致这段代码的 SQL 语句“双重执行”的原因:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PostBackOptions optionsSubmit = new PostBackOptions(btn_Add);
            btn_Add.OnClientClick = "disableButtonOnClick(this, 'Please wait...', 'disabled_button ui-corner-all'); ";
            btn_Add.OnClientClick = ClientScript.GetPostBackEventReference(optionsSubmit);
        }
    }

当我将其注释掉时,会添加一次信息,但按钮并没有像我想要的那样被禁用。禁用该按钮将防止人们不耐烦并多次单击该按钮。

建议?

这是我得到的:

aspx

<asp:Button ID="btn_Add" Text="Add" CssClass="ui-state-default ui-corner-all" runat="server" OnClick="btn_Add_Click" />

aspx.cs

if (!Page.IsPostBack)
{
    PostBackOptions optionsSubmit = new PostBackOptions(btn_Add);
    btn_Add.OnClientClick = "disableButtonOnClick(this, 'Please wait...', 'disabled_button ui-corner-all'); ";
    btn_Add.OnClientClick += ClientScript.GetPostBackEventReference(optionsSubmit);
}

执行两次 SQL 语句

aspx

<asp:Button ID="btn_Add" Text="Add" CssClass="ui-state-default ui-corner-all" runat="server" />

aspx.cs

if (!Page.IsPostBack)
{
    PostBackOptions optionsSubmit = new PostBackOptions(btn_Add);
    btn_Add.OnClientClick = "disableButtonOnClick(this, 'Please wait...', 'disabled_button ui-corner-all'); ";
    btn_Add.OnClientClick += ClientScript.GetPostBackEventReference(optionsSubmit);
}

以所需的方式简单地更改“btn_Add”,但不执行“btn_Add_Click”的代码

aspx

<asp:Button ID="btn_Add" Text="Add" CssClass="ui-state-default ui-corner-all" runat="server" OnClick="btn_Add_Click" />

aspx.cs

if (!Page.IsPostBack)
{
    PostBackOptions optionsSubmit = new PostBackOptions(btn_Add);
    btn_Add.OnClientClick = "disableButtonOnClick(this, 'Please wait...', 'disabled_button ui-corner-all'); ";
    //btn_Add.OnClientClick += ClientScript.GetPostBackEventReference(optionsSubmit);
}

以所需的方式更改“btn_Add”,不执行“btn_Add_Click”的代码,并将整个页面刷新到 Equipment.aspx(通常 Equipment.aspx 通过 jquery .load 事件加载到 div 中)

【问题讨论】:

  • 请考虑使用 using 语句,清理大量代码并为您正确关闭所有内容
  • 我会将上面的代码放在一个单独的函数中并单独测试它。除了连接和调用数据库之外,还有很多事情可能发生。
  • @Jesus 说真话。
  • 检查 EventArgs 是否有正确的事件?
  • 在您链接到重复的问题中,该问题是由函数被命中两次引起的。如果你在函数的顶部放置一个断点,它只会被命中一次吗?

标签: c# sql sql-server-2008


【解决方案1】:

一些建议...

  • 连接字符串应该存储在您的 web.config 文件中。

  • 可以在整个过程中捕获每个步骤的异常,但使用“使用”语句。这样您就不必担心如何处理您的对象。

  • 我建议将 Global.asax 文件添加到您的项目中并在其中捕获应用程序错误。在您的 catch 语句中,您可以放置​​一行并说“throw new Exception..”并传入您的特定异常,这样很容易捕获并且您可以描述错误。然后我建议在 Enterprise Library 5.0 中设置 Logging 应用程序块。拥有像您这样的全局“错误”变量可能不是一个好主意。如果您想轻松学习 Enterprise Library,请下载 Enterprise Library Labs 示例。

  • 我不会在您的代码中直接使用 SQL 命令。我会使用存储过程,并在 SQL 服务器本身上完成 SQL。如果您有变量,请在存储过程上设置参数。存储过程对您的 Web 应用程序更安全。使用 Microsoft 企业库中的数据库应用程序块甚至可能是一个好主意。他们为您准备了所有这些代码,您只需要导入库并了解命令即可。他们为您处理所有的性能影响。

  • 如果使用 using 语句,则无需关闭连接或处置。我在代码中删除了它。

  • 如果你抛出一个异常,就不需要“return”语句……下一个符合条件的catch语句(或finally语句)将捕获它。如果没有,那么 Global.asax 中的 Application_Error 将捕获它。确保在 .NET 框架中正确处理未处理的异常。 Microsoft 打破了 .NET 3.5 未处理异常架构,因此您要么必须添加自己的模块,要么切换回 1.1 架构。或者升级到 .NET 4.0。

  • 实际问题:您的 click 事件可能会被调用两次,因为您使用的是处理程序,并且您的

这里是#1: OnClick="btn_Add_Click" />

这里是#2: btn_Add.OnClientClick = ClientScript.GetPostBackEventReference(optionsSubmit);

如果您的控件具有 onclick 属性,则无需添加特殊代码(如 OnClientClick 或事件处理程序)。只需使用 1 或其他。

祝你好运!


        error.InnerHtml = "&nbsp;";

        string connStr = "Data Source=.\\SQLEXPRESS;"
            + "Initial Catalog=SIMON;"
            + "Persist Security Info=True;"
            + "User ID=username;Password=password");

        using (SqlConnection MyConn = new SqlConnection(connStr))
        {
            string sqlStatement = @"INSERT INTO [Network_Equipment] "
                + "([Network_Equipment_Name], [Network_Equipment_Type_ID], [IP_Address], [FQDN], [NetBIOS_Name], [Building_ID], [Description])"
                + " VALUES "
                + "(@Network_Equipment_Name, @Network_Equipment_Type_ID, @IP_Address, @FQDN, @NetBIOS_Name, @Building_ID, @Description)";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, MyConn);
            sqlCmd.Connection = MyConn;

            sqlCmd.Parameters.AddWithValue("@Network_Equipment_Name", ((in_Add_Equipment.Value == null) ? (object)DBNull.Value : (object)in_Add_Equipment.Value));
            sqlCmd.Parameters.AddWithValue("@Network_Equipment_Type_ID", ((ddl_Equipment_Type.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Equipment_Type.SelectedValue));
            sqlCmd.Parameters.AddWithValue("@IP_Address", ((in_IP_Address.Value == null) ? (object)DBNull.Value : (object)in_IP_Address.Value));
            sqlCmd.Parameters.AddWithValue("@FQDN", ((in_FQDN.Value == null) ? (object)DBNull.Value : (object)in_FQDN.Value));
            sqlCmd.Parameters.AddWithValue("@NetBIOS_Name", ((in_NetBIOS.Value == null) ? (object)DBNull.Value : (object)in_NetBIOS.Value));
            sqlCmd.Parameters.AddWithValue("@Building_ID", ((ddl_Building.SelectedValue == null) ? (object)DBNull.Value : (object)ddl_Building.SelectedValue));
            sqlCmd.Parameters.AddWithValue("@Description", ((ta_Description.Value == null) ? (object)DBNull.Value : (object)ta_Description.Value));

            try
            {
                MyConn.Open();
            }
            catch (Exception er)
            {
                //error.InnerHtml = er.ToString();
                //return;
                throw new Exception(...
            }

            try
            {
                sqlCmd.ExecuteNonQuery();
            }
            catch (Exception er)
            {
                //error.InnerHtml = er.ToString();
                //return;
                throw new Exception(...
            }

            error.InnerHtml = "Successfully added: " + in_Add_Equipment.Value;
        }

        in_Add_Equipment.Value = "";
        ddl_Equipment_Type.SelectedIndex = 0;
        in_IP_Address.Value = "";
        in_FQDN.Value = "";
        in_NetBIOS.Value = "";
        ddl_Building.SelectedIndex = 0;
        ta_Description.Value = "";

        GridView1.DataBind();

【讨论】:

  • 这是一个按钮点击事件。它应该只在回发时运行。
  • 为什么捕获一个异常只是为了抛出另一个异常?完全取出异常处理程序,除非您的代码可以对异常做一些有用的事情(在这种情况下,它可能应该捕获SqlException,检查错误,并确定它是否是可以处理的问题,或者应该重新抛出)
  • 您可能需要添加自定义消息以使其更直观
【解决方案2】:

去掉两个catch中的“return”

为每次尝试添加 finally 语句

并移动

 sqlCmd.Dispose();             sqlCmd = null;             MyConn.Close(); 

进入最后

调试的时候可以看到insert语句是否正确。然后查看数据库。

【讨论】:

    【解决方案3】:

    @Jesus Ramos 是正确的。

    做这样的事情。

    private _constring = new SqlConnection("Data Source=.\\SQLEXPRESS;"
            + "Initial Catalog=SIMON;"
            + "Persist Security Info=True;"
            + "User ID=username;Password=password");
    
    
    protected void btn_Add_Click(object sender, EventArgs e)
       {
    
            SqlTransaction trans = null;
            using (var con = new  SqlConnection(_constring))
            {
                con.Open();
                trans = con.BeginTransaction();
                using (
    
                     string sqlStatement ="//SqlStuff";
    
                    var  sqlCmd = new  SqlCommand(sqlStatement,con))
                {
                     sqlCmd.Transaction = trans;
                     sqlCmd.Connection = con;
    
                    try
                    {
    
    
                        //sqlcmd.Parameters Stuff
    
    
                        sqlCmd.ExecuteNonQuery();
                        trans.Commit();
    
                       //SUCCESS
                    }
                   catch (Exception er)
                   {
                   error.InnerHtml = er.ToString();
                   return;
                    }
                    finally
                    {
                        con.Close();
                    }
    
                }
            }
        }
    

    问候

    【讨论】:

      【解决方案4】:

      除了它们在一个函数中的代码过多、不使用using 语句等之外,这个事件处理函数会被多次调用的唯一原因是它被多次连接。检查您的 AutoEventWireUp 设置、按钮上 OnClick 定义的代码前面以及代码隐藏中的显式事件连接(可能看起来像 btn_Add.Click += btn_Add_Click;

      【讨论】:

        猜你喜欢
        • 2012-01-11
        • 2014-05-23
        • 2013-03-07
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多