在服务器资源管理器中添加连接时出错:“无法添加数据连接.ExecuteScalar需要打开且可用的连接。”

时间:2010-09-13 18:59:46

标签: .net sql-server visual-studio

我正在使用Visual Studio 2008,而我的数据库是SQL Server 2000。

我想在VS中添加与Server Explorer的连接。数据源是Microsoft SQL Server(SqlClient)。输入我的所有信息后,单击“测试连接”,即可成功。

但是当我点击OK时,我收到错误:

无法添加数据连接。 ExecuteScalar需要一个开放且可用的连接。连接的当前状态已关闭。

3 个答案:

答案 0 :(得分:11)

重新启动Visual Studio。然后,重新启动计算机。

答案 1 :(得分:0)

您可以打开服务器资源管理器(View - > Server Explorer)重新连接连接。

您可以删除当前连接以再次打开相同的连接。

答案 2 :(得分:0)

对于那些使用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
            }
        }
相关问题