尝试使用 C# 连接到 SQL Server 时出错 [英] Error trying to connect to SQL Server using C#

查看:50
本文介绍了尝试使用 C# 连接到 SQL Server 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";
SqlConnection con;
con = new SqlConnection(constring);
con.Open();
string query="SELECT * from CadPoolProjectTable1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("selected");
con.Close(); 

我在 con.Open(); 行出错.错误是:

I am getting error at the line con.Open();. The error is:

与网络相关或特定于实例的建立时发生错误连接到 SQL Server.服务器未找到或无法访问.验证实例名称是否为正确,并且 SQL Server 是配置为允许远程连接.(提供者:命名管道提供程序,错误:40 - 无法打开连接到 SQL Server)

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

推荐答案

您缺少一个;"在连接字符串中的服务器名称之后.

You are missing a ';' after the server name in the connection string.

string constring = "Data Source=132.186.127.169"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";

应该是

string constring = "Data Source=132.186.127.169;"+ "Initial Catalog=CadPool1;" + "Integrated Security=True";

错误表明您的应用无法连接到服务器.我会做以下事情.

The error says that your app was not able to connect to the server. I would do the following.

  1. 检查服务器地址(快速查看它看起来不错)
  2. 使用 management studio 连接,在您的情况下它应该可以工作.

这意味着问题出在代码上.由于您正在连接字符串,因此我将调试代码并查看连接字符串的最终结果是什么.

It means the issue is with the code. Since you are concatenating the string I would debug the code and see what the end result for the connection string is.

提示:如果是 Web 应用程序,请将连接字符串添加到 web.config 文件中.此处的更多信息如何:从 Web.config 文件读取连接字符串

Tip:If it is a web application add the connection string to web.config file. More info here How to: Read Connection Strings from the Web.config File

这篇关于尝试使用 C# 连接到 SQL Server 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆