【问题标题】:Could not open a connection to SQL Server 2012无法打开与 SQL Server 2012 的连接
【发布时间】:2014-05-11 07:10:23
【问题描述】:

喂,

我在 MS Visual Studio 2012 下使用 SQL Server 2012。

下面是我来自 app.config 的连接字符串

<add key="Platform" value="Data Source=Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>

还有我的连接类

static SqlConnection con;
        public static SqlConnection GetConnection()
        {
            con = new SqlConnection(ConfigurationManager.AppSettings["Platform"].ToString());
            return con;
        }

 internal void AddCustomer (Buyer customer, User user, PlatformType type )
        {
            SqlConnection conn = DALConnection.GetConnection();

            try
            {
                SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                 ...

                con.Open();
                cmd.ExecuteNonQuery();

我的数据库存储在我的项目文件夹下。

我尝试使用我的方法时遇到的错误是:

无法打开与 SQL Server 2012 的连接

此致,

【问题讨论】:

  • 看来问题不在你的代码上。我建议先使用外部工具测试连接。我推荐UDL file

标签: c# sql sql-server


【解决方案1】:

您的连接对象错误,您在 Command 中传递了conn,而对于打开连接,您使用的是con 对象而不是conn

con.Open();

使用:

conn.Open();

你的代码会是这样的:

try
            {
                SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                conn.Open();
                cmd.ExecuteNonQuery();
             }

【讨论】:

  • 在 OP 的代码中,con == conn(两个不同的变量,但它们会得到相同的连接对象),所以没关系。
  • 但是往下看,OP 在 Command 中传递 conn 而 OP 使用的是 con.Open() 而不是 conn.Open()
【解决方案2】:

虽然您的代码有一些问题,但它似乎应该可以工作。
尝试使用独立的连接工具测试您的连接字符串。
要测试connection string,请查看this SO thread

正如@hvd 在其中一个 cmets 中提到的那样,您的代码令人困惑,因为您有 con,它等同于 conn。这使您的代码难以遵循。我建议你重构它,这样你(和其他人)会更容易理解。

祝你好运!

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
  • @jaap 我同意你的评论,但不认为它适用于此。这不是critique or request clarification。错误消息表明问题出在连接字符串中。我已经建议如何检查这个问题,在我看来,一旦连接问题解决了,他的问题就会解决。没有他的网络结构,不可能给出更具体的解决方案。
  • 我认为你的回答更像是一个评论/建议而不是一个答案,因为它只是为解决方案提供了一个方向,而不是一个解决方案
【解决方案3】:

试试这个:

<add key="Platform" value="Data Source=.\Bigfoot2;Initial Catalog=Platform;Integrated Security=True"/>

【讨论】:

  • .\是什么意思??
  • @EhsanSajjad '.'表示本地主机。您可以替换“。”使用您的 IP 地址或计算机名称。
【解决方案4】:

如果您的 SQL Server 与 Visual Studio 或应用程序位于不同的计算机上,Windows 防火墙中是否打开了所需的端口?

尝试以下步骤: http://blog.sujay.sarma.in/2013/12/19/SCRIPT-Open-ports-in-Windows-Firewall-for-SQL-Server-connectivity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多