Can't make a connection string in c#

江枫思渺然 提交于 2019-12-14 04:01:55

问题


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

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!

Here is my code:

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

This is the exception error:

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)

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

Thank you


回答1:


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

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.



来源:https://stackoverflow.com/questions/36375366/cant-make-a-connection-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!