【问题标题】:Error adding connection in Server Explorer: "Unable to add data connection. ExecuteScalar requires an open and available connection."在服务器资源管理器中添加连接时出错:“无法添加数据连接。ExecuteScalar 需要打开且可用的连接。”
【发布时间】:2010-09-13 18:59:46
【问题描述】:
我使用的是 Visual Studio 2008,我的数据库是 SQL Server 2000。
我想在 VS 中添加到服务器资源管理器的连接。数据源是 Microsoft SQL Server (SqlClient)。输入我所有的信息后,点击测试连接,就成功了。
但是当我点击确定时,我得到了错误:
无法添加数据连接。 ExecuteScalar 需要一个开放且可用的连接。连接的当前状态为关闭。
【问题讨论】:
标签:
.net
sql-server
visual-studio
【解决方案1】:
重启Visual Studio。然后,重新启动您的计算机。
【解决方案2】:
您可以打开服务器资源管理器(查看 -> 服务器资源管理器)重新连接。
您可以删除当前连接以再次打开相同的连接。
【解决方案3】:
对于那些使用 SQL 命令并收到错误“无法添加数据连接。ExecuteScalar 需要一个打开且可用的连接。连接的当前状态为关闭”的用户。试试这个:
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
}
}