gpt4 book ai didi

c# - SellectCommad.connection 属性未初始化

转载 作者:行者123 更新时间:2023-11-30 19:19:30 26 4
gpt4 key购买 nike

当我调试我的应用程序时,出现 SelectCommand.Connection 属性未初始化的错误。我不知道我在这里做错了什么:s。我实际上想在我对文本框的文本更改事件的搜索中添加一个过滤器。

public class ConnectionClass
{
static SqlConnection cn;

public static SqlConnection Connection()
{
string myConnection = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
if (cn != null)
{
cn = new SqlConnection(myConnection);
cn.Open();
}
return cn;
}

}

public class ClassDataManagement
{
SqlConnection cn = ConnectionClass.Connection();

public DataTable GetData(string SQL)
{
SqlCommand cmd = new SqlCommand(SQL, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}

protected void TextBoxFilterText_TextChanged(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
string query = "Select CourseCode from _Courses where coursecode like'%" + TextBoxFilterText.Text.TrimEnd() + "%'";
dm.GetData(query);
GridViewCourses.DataBind();
}

最佳答案

那是因为您的cn 变量是null,并且没有被初始化。另一个例子说明为什么在静态方法中初始化和打开数据库连接是个坏主意。

试试这个:

public class ClassDataManagement 
{
public DataTable GetData(string SQL)
{
string YourConnectionString = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
DataTable dt = new DataTable();

using (SqlConnection cn = new SqlConnection(YourConnectionString))
using (SqlCommand cmd = new SqlCommand(SQL, cn))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return dt;
}
}

使用 SqlDataAdapter 类,您不需要显式调用 SqlConnection.Open()SqlDataAdapter.Fill() 方法处理所有连接打开(和关闭)。

MSDN Reference on SqlDataAdapter.Fill()

根据上述引用,引用:

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

关于c# - SellectCommad.connection 属性未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9167688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com