gpt4 book ai didi

c# - 无法在 C# 中创建连接字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:26 24 4
gpt4 key购买 nike

我是 C# 新手,了解不多!

我已经在 C# 2012 中创建了一个本地数据库,并希望与其建立连接。我用它的向导测试了连接,它说成功连接到数据库。

所以我将连接字符串地址复制到我的代码中,但在运行几秒钟后出现异常错误!

不知道问题出在哪里!

这是我的代码:

System.Data.SqlClient.SqlConnection myConnection;

private void Form1_Load(object sender, EventArgs e)
{
myConnection = new System.Data.SqlClient.SqlConnection();
myConnection.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\\Users\\jack\\Documents\\Visual Studio 2012\\Projects\\dictionary\\dictionary\\dictionaryDb.mdf;Integrated Security=True;Connect Timeout=30";
myConnection.Open();

MessageBox.Show("successfully connected!");
}

这是异常错误:

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)

我的另一个问题是:SQL Server Express 和 C# 中的本地数据库之间有区别吗?

谢谢

最佳答案

您似乎漏掉了一个反斜杠 \(LocalDB) 之间和 v11.0 :

myConnection.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\jack\\Documents\\Visual Studio 2012\\Projects\\dictionary\\dictionary\\dictionaryDb.mdf;Integrated Security=True;Connect Timeout=30";

一个反斜杠将被视为转义字符,两个反斜杠 \\将被视为 backslash .或者,执行此操作(使用 @ )以使您的字符串字符更清晰:

myConnection.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\jack\Documents\Visual Studio 2012\Projects\dictionary\dictionary\dictionaryDb.mdf;Integrated Security=True;Connect Timeout=30";

您还可以指定您的 connectionString在你的app.config <connectionStrings> <add name="DefautConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\jack\Documents\Visual Studio 2012\Projects\dictionary\dictionary\dictionaryDb.mdf;Integrated Security=True;Connect Timeout=30;" ..等等这并不少见。

关于c# - 无法在 C# 中创建连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com