使用 "Using(conn)" 时如何关闭连接,因为它在连接未初始化的另一个方法中导致错误。

How close a connection when using "Using(conn)" as it is causing error within another method that the connection isn't initialized.

我有一个页面使用连接字符串显示来自数据库的信息,一个是 SqlDataReader,我在其中打开和关闭连接。另一个是

Using(conn)
{
}

Using 在 open/close 函数之前运行,发生这种情况时会导致连接未正确初始化的错误。当不调用 Using() 函数时,一切都很好。如果我再次在 SqlDataReader 函数中设置连接字符串,它可以正常工作,但之前设置的字符串只是空的。

我是 asp.net 的新手,我不确定在页面上使用 Using() 是否是一种不好的做法。

我在页面加载时设置了连接字符串,但是如果 Using() 是 运行 连接字符串总是空的:

    public SqlConnection conn;
    String albumID;

    protected void Page_Load(object sender, EventArgs e)
    {
        conn= new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\connstring.mdf;Integrated Security=True");
        thing1();
        thing_using_Using();
        conn_open_conn_close_thing();
        thing2();
    }

Using() 函数:

    public void isAlreadyLiked()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Likes WHERE UserID = @userID AND AlbumID = @albumID", conn);
        using (conn)
        {
            sda.SelectCommand.Parameters.AddWithValue("@userID", Session["loggedID"]);
            sda.SelectCommand.Parameters.AddWithValue("@albumID", albumID);

            sda.Fill(dt);

            if (dt.Rows.Count == 0)
            {
                //place Like button here
            }
            else
            {
                //place Unlike button here
            }
        }
    }

仅使用 .open 和 .close 的函数:

    public void albumDetails()
    {        
    //if the conn string is set here again its fine, but I don't want to repeat the conn string over and over.    

        SqlCommand comm = new SqlCommand("SELECT * FROM Albums WHERE AlbumID=" + albumID, conn);
        conn.Open();
        SqlDataReader reader = comm.ExecuteReader();
        while (reader.Read())
        {
            string AlbumName = reader["AlbumName"].ToString();
            string AlbumArtist = reader["AlbumArtist"].ToString();
            lblAlbumName.Text += AlbumName;
            lblAlbumArtist.Text += AlbumArtist;
        }
        reader.Close();
        conn.Close();
    }

将连接字符串保留为全局变量,或者最好从 web.config 中读取它,并在每次需要时重新创建 SqlConnection,使用后立即销毁它。

这是针对连接等一次性对象的推荐做法,毕竟使用 Connection Pooling 您不必担心性能问题

// Here is as fixed text and this could be probematic if 
// you need to deploy to another environment. 
// Better to read it from your web.config
public string conString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\connstring.mdf;Integrated Security=True"
...

protected void Page_Load(object sender, EventArgs e)
{
  ....
}

public void isAlreadyLiked()
{
    DataTable dt = new DataTable();
    using(SqlConnection con = new SqlConnection(conString))
    using(SqlDataAdapter sda = new SqlDataAdapter(".....", conn);
    {
        ......
    }
}

public void albumDetails()
{        
    using(SqlConnection con = new SqlConnection(conString))
    using(SqlCommand comm = new SqlCommand(".....", conn);
    {
        conn.Open();
        using(SqlDataReader reader = comm.ExecuteReader())
        {
            while (reader.Read())
            {
                ...
            }
        }
    }
}