连接关闭错误

时间:2016-07-18 15:47:47

标签: asp.net sql-server-2008-r2

我在这段代码中有两个DataReader,vs给我这个错误"连接没有关闭。连接的当前状态是开放的。"错误来自connection2。我查看我的代码,但我的两个连接已关闭。问题出在哪里?

     protected void Page_Load(object sender, EventArgs e)
{

    using (SqlConnection connection1 = DBConnection.getConnection())
    {
        string strquery1 = " with distinctvalueyes (typearticle) as (select top 1 'Fruit' FROM WeedingSalonGeneralRes where Fruit=1  union all select top 1 'Drink' FROM WeedingSalonGeneralRes where Drink=1 union all select top 1 'Desert' FROM WeedingSalonGeneralRes where Desert=1  union all select top 1 'MainFood' FROM WeedingSalonGeneralRes where MainFood=1 union all select top 1 'Salad' FROM WeedingSalonGeneralRes where Salad=1 union all select top 1 'TableFlower' FROM WeedingSalonGeneralRes where TableFlower=1 union all  select top 1 'SaloonLighting' FROM WeedingSalonGeneralRes where SaloonLighting=1 union all  select top 1 'Saloondesign' FROM WeedingSalonGeneralRes where Saloondesign=1 union all select top 1 'SloonCrew' FROM WeedingSalonGeneralRes where SloonCrew=1  union all  select top 1 'Pastry' FROM WeedingSalonGeneralRes where Pastry=1 union all  select top 1 'GiftCard' FROM WeedingSalonGeneralRes where GiftCard=1 )  select * from distinctvalueyes ";
        connection1.Open();
        SqlCommand cmd1 = new SqlCommand();
        cmd1.Connection = connection1;
        cmd1.CommandText = strquery1;
        string cis = Session["customerID"].ToString();
        lbl2_customerid.Text = cis;

        SqlDataReader reader = cmd1.ExecuteReader();
        if (reader.Read())
        {
            lbl8_fruit.Text = reader[0].ToString();

            // wrapped in a using block, connection will now always be closed and disposed
            using (SqlConnection connection2 = DBConnection.getConnection())
            {
                //query for fetch service prices 
                string strquery2 = "SELECT Fruit_price,Drink_price,Desert_price,MainFood_price,Salad_price,TableFlower_price,SaloonLighting_price,SaloonDesign_price,SaloonCrew_price,Pastry_price,GiftCard_price  FROM GenReservationServicePrice";
                connection2.Open();
                SqlCommand cmd2 = new SqlCommand();
                cmd2.Connection = connection2;
                cmd2.CommandText = strquery2;
                SqlDataReader reader2 = cmd2.ExecuteReader();
                if (reader2.Read())
                {
                    string Fruit_price;
                    string Drink_price;
                    string Desert_price;
                    string MainFood_price;
                    string Salad_price;
                    string TableFlower_price;
                    string SaloonLighting_price;
                    string SaloonDesign_price;
                    string SaloonCrew_price;
                    string Pastry_price;
                    string GiftCard_price;


                    Fruit_price = reader[0].ToString();
                    Drink_price = reader[1].ToString();
                    Desert_price = reader[2].ToString();
                    MainFood_price = reader[3].ToString();
                    Salad_price = reader[4].ToString();
                    TableFlower_price = reader[5].ToString();
                    SaloonLighting_price = reader[6].ToString();
                    SaloonDesign_price = reader[7].ToString();
                    SaloonCrew_price = reader[8].ToString();
                    Pastry_price = reader[9].ToString();
                    GiftCard_price = reader[10].ToString();


                    lbl8_fruit.Text = Fruit_price;

                }
            }
        }
    }
}



///connection class 
public class DBConnection
{
 private static SqlConnection connection=null;
 public DBConnection()
{

}

public static SqlConnection getConnection()
{
    if (connection != null)
    { return connection; }
    else
    {
        String connectionString = WebConfigurationManager.AppSettings["connectionString"];
        connection = new SqlConnection(connectionString);
        return connection;
    }
}

}

1 个答案:

答案 0 :(得分:0)

修改

问题是你试图在2个地方使用相同的SqlConnection实例。每次需要时,您应该使用新的SqlConnection

  • 创建
  • 使用它
  • 处理它

代码更改:

///connection class 
public class DBConnection
{
    public static SqlConnection getConnection()
    {
        String connectionString = WebConfigurationManager.AppSettings["connectionString"];
        return new SqlConnection(connectionString);
    }
}

Sql Server有一个名为Connection Pooling的东西,默认情况下启用它。在c#中创建连接会重用Sql Server上已有的连接,因此这个操作非常便宜。包含使用SqlConnections块中using的所有代码,以确保它们始终处于关闭状态,因此您没有连接泄漏。

app.config / web.config也有一个ConnectionString section。您应该使用它而不是应用程序设置。

使用SqlConnection

您应该将所有SqlConnection个实例包装在using块中。这将确保即使发生异常,也始终关闭和释放连接。它也可以完成代码中的所有检查工作,无需查看它是否在关闭时打开。

以下是您使用using块更改的代码,我删除了一些逻辑,因此很清楚我所做的更改。

protected void Page_Load(object sender, EventArgs e)
{
    /* your existing code removed for clarit */

    // wrapped in a using block, connection will now always be closed and disposed
    using(SqlConnection connection1 = DBConnection.getConnection())
    {
        connection1.Open();
        SqlCommand cmd1 = new SqlCommand();
        cmd1.Connection = connection1;
        cmd1.CommandText = strquery1;
        string cis = Session["customerID"].ToString();
        lbl2_customerid.Text = cis;

        SqlDataReader reader = cmd1.ExecuteReader();
        if (reader.Read())
        {
            /* your existing code removed for clarit */

            // wrapped in a using block, connection will now always be closed and disposed
            using(SqlConnection connection2 = DBConnection.getConnection())
            {
                connection2.Open();
                SqlCommand cmd2 = new SqlCommand();
                cmd2.Connection = connection2;
                cmd2.CommandText = strquery2;
                SqlDataReader reader2 = cmd2.ExecuteReader();
                if (reader2.Read())
                {
                    /* your existing code removed for clarit */
                }
            }
        }
    }
}