我正在使用Visual Studio 2008,我的数据库是SQL Server 2000。
我想在VS的Server Explorer中添加一个连接。数据源是Microsoft SQL Server(SqlClient)。在输入所有信息并单击测试连接后,连接成功。
但是当我单击确定时,出现错误:
无法添加数据连接。ExecuteScalar需要已打开且可用的连接。连接的当前状态为关闭。
我正在使用Visual Studio 2008,我的数据库是SQL Server 2000。
我想在VS的Server Explorer中添加一个连接。数据源是Microsoft SQL Server(SqlClient)。在输入所有信息并单击测试连接后,连接成功。
但是当我单击确定时,出现错误:
无法添加数据连接。ExecuteScalar需要已打开且可用的连接。连接的当前状态为关闭。
重新启动Visual Studio
,然后重新启动您的计算机。
你可以打开服务器资源管理器(视图 -> 服务器资源管理器)重新连接。
你可以删除当前的连接再次打开同一个连接。
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
// query to select all the rows whose column name is the same as id
comm.CommandText = "SELECT COUNT(*) from tableName where colName like @val1";
comm.Connection = conn;
conn.Open(); // <---- adding this line fixed the error for me
comm.Parameters.AddWithValue("@val1", id);
// retrieve how many rows are returned after executing the query
count = (int)comm.ExecuteScalar(); // < --- where the error originally occurred
}
}