在 C# 中连接到 SQL Server 时出现问题

Posted

技术标签:

【中文标题】在 C# 中连接到 SQL Server 时出现问题【英文标题】:Having problems connecting to SQL Server in C# 【发布时间】:2019-08-06 10:47:31 【问题描述】:

我正在尝试连接到 SQL Server。

我正在尝试在 C# 中使用 SqlConnection 对象,我尝试在我的用户名之前放置一个域,我尝试使用和不使用端口号

SqlConnection myConnection = new SqlConnection("user id=username;" +
                                   "password=xxxxx;" +
                                   "server=ipaddress:portnumber;" +
                                   "Trusted_Connection=yes;" +
                                   "database=databaseName; " +
                                   "connection timeout=30");

try

    myConnection.Open();

catch(Exception ex)


我没有收到任何错误消息,它只是挂在myConnection.Open

【问题讨论】:

试试"server=ipaddress;",或者如果这不起作用,试试"server=ipaddress,portnumber;" - 用逗号,)分隔IP地址和端口号,不是冒号... 您将Trusted_Connection 设置为yes,但还传递了用户名和密码的值。这是其中之一;你真的想用哪个? @Larnu 不会是Integrated Security=True Integrated SecurityTrusted_Connection 是同义词,@Filburt: What is the difference between Trusted_Connection and Integrated Security in a connection string? 我删除了 Trusted_Connection 行,因为我想使用用户名和密码进行连接。我也尝试过 Marcs 的建议,但它仍然会以相同的方式做出反应并在尝试打开连接时挂起 【参考方案1】:

您尝试这种格式的连接字符串。请找到此链接以获取有关 c# link 中的连接字符串的更多信息

    // To avoid storing the connection string in your code, 
    // you can retrieve it from a configuration file.
    SqlConnection myConnection = new SqlConnection("Data Source=ipaddress;
                                                  Initial Catalog=dbname;
                                                  User Id=userid; 
                                                  Password=pass;");

【讨论】:

【参考方案2】:

正如@marc_s 在 cmets 中已经提到的,端口# 必须与 逗号 一起指定,在您的情况下,它应该像 server=ipaddress,portnumber;

不过,these steps 可以帮助您快速解决 SQL Server 的连接问题

【讨论】:

以上是关于在 C# 中连接到 SQL Server 时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

尝试在 C# 中连接到 Oracle DB 时出现问题

无法在 Eclipse 中连接到新 SQL Server

如何在 CodeIgniter 中连接到 SQL Server 数据库?

如何在 R 中连接到 SQL Server 数据库

无法使用 JDBC 在 android 中连接到 sql server 2008

尝试在 C# 中连接到 Excel 电子表格