【发布时间】:2026-01-12 06:25:01
【问题描述】:
我有一个页面,它使用连接字符串显示来自数据库的信息,其中一个是 SqlDataReader,我在其中 .open 和 .close 连接。另一个是
Using(conn)
{
}
Using 在打开/关闭函数之前运行,发生这种情况时会导致连接未正确初始化的错误。当未调用 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();
}
【问题讨论】:
-
每个方法都应该打开和关闭它自己的连接。让微软通过连接池自行管理连接。这样您的应用程序中就不会出现连接混乱。
标签: sql asp.net initialization using