在循环中运行插入存储过程的最佳/正确方法c#

时间:2017-03-20 14:24:47

标签: c# asp.net sql-server stored-procedures foreach

我坚持正确地运行存储过程以通过foreach循环插入记录的方法。

这是我到目前为止所拥有的。

    string constr = ConfigurationManager.ConnectionStrings["CurrencyDb"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr)) {
    con.Open();
        foreach (ListItem i in DependenciesListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertDependency", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CurrencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@DependencyId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding dependencies. " + ex.Message);
                    }
                }
            }
        }

        foreach (ListItem i in AffectedListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertAffected", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@DependencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@CurrencyId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding affected apps. " + ex.Message);
                    }
                }
            }
        }

        //Loops through Platform list box and for each item that's selected, add a record into the platform table in the database.
        foreach (ListItem i in PlatformListBox.Items) {
            if (i.Selected) {
                using (SqlCommand cmd = new SqlCommand("dbo.InsertPlatform", con)) {
                    try {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@CurrencyId", scopeidentity);
                        cmd.Parameters.AddWithValue("@PlatformId", i.Value);
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqlex) {
                        throw new Exception("SQL Exception on insert. " + sqlex.Message);
                    }
                    catch (Exception ex) {
                        throw new Exception("Error adding platforms. " + ex.Message);
                    }
                }
            }
        }
    }

这样做,我收到以下错误(更新)

Uncaught Error: Sys.WebForms.PageRequestManagerServerErrorException: Error adding dependencies. The connection was not closed. The connection's current state is open.
    at Function.Error.create (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._createPageRequestManagerServerError (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._parseDelta (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Sys.WebForms.PageRequestManager._onFormSubmitCompleted (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at Array.<anonymous> (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1
    at Sys.Net.WebRequest.completed (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)
    at XMLHttpRequest._onReadyStateChange (MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1)

有人能让我知道做这种事情的最佳做法是什么?非常感谢你。

1 个答案:

答案 0 :(得分:1)

请勿多次致电con.Open();。将其移至

using (SqlConnection con = new SqlConnection(constr)) {
  con.Open();
  ...

请参阅例外表中的第一行:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx