本文介绍了无法在 C# 中创建连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to C# and don't know much!

我在 C# 2012 中创建了一个本地数据库,并想建立一个连接.我用它的向导测试了连接,它说成功连接到数据库.

I have created a local database in C# 2012 and want to make a connection to it. I tested connection with its wizard and it said successfully connected to database.

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

So I copied connection string address to my code but after few seconds of running i have and exception error!

我不知道问题出在哪里!

I don't know where the problem is!

这是我的代码:

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!");
}

这是异常错误:

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

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

And my other question is: is it differences between SQL Server Express and local database in C#?

谢谢

推荐答案

你好像漏掉了 (LocalDB)v11.0 之间的一个反斜杠 \:

It seems like you miss one backslash \ between (LocalDB) and 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";

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

One back slash will be consider as escape character, two backslashes \\ will be treated as backslash. Alternative, do this (using @) to make your string character clearer:

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";

您还可以在 app.config 中指定您的 connectionString<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;" .. 等等,这种情况并不少见.

You could also specify your connectionString in your 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;" .. and so on which is not uncommon.

这篇关于无法在 C# 中创建连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 03:01
查看更多