简体   繁体   English

使用代码连接到数据库-C#

[英]Connecting to database using code - C#

When I use server explorer in Visual Studio and add a local DB on my D drive, I get a connection string and the connection test is successful. 当我在Visual Studio中使用服务器资源管理器并在D驱动器上添加本地数据库时,我得到一个连接字符串,连接测试成功。

But when I want to use that connection string like below to attach the database without the wizard and jut by code, I get an error on opening the connection, my connection string is provided below: 但是,当我想像下面那样使用该连接字符串在没有向导的情况下附加数据库并按代码突出显示时,打开连接时出现错误,下面提供了我的连接字符串:

string coonection_string ="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";

try
{
      SqlConnection myconnection = new SqlConnection(coonection_string);
      myconnection.Open();
      MessageBox.Show(" connected");
}
catch (Exception e1)
{
      MessageBox.Show(e1.ToString());
}

Your connection string is wrong. 您的连接字符串错误。 Eigher mdf file in your local project or sqlexpres or you can use a database name in the connection string like 您可以在本地项目或sqlexpres中找到mdf文件,也可以在连接字符串中使用数据库名称,例如

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True

or 

Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;

Check this link. 检查此链接。

DB Connection string in Web.config to use attached .mdf database won't work Web.config中的数据库连接字符串无法使用附加的.mdf数据库

Always use Web.config file for connection string and access the entry in code as 始终使用Web.config文件作为连接字符串,并以如下方式访问代码中的条目

Dim mWebSvr As String = ConfigurationSettings.AppSettings("Connectionstring")

Keep an @ symbol in-front of the connection string,in C# backslash is a escape character 在连接字符串的前面保留一个@符号,在C#中,反斜杠是转义字符

string coonection_string =@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";

else your connection string may not be in correct format 否则您的连接字符串格式可能不正确

SqlConnectionStringBuilder.AttachDBFilename Property SqlConnectionStringBuilder.AttachDBFilename属性

Try to put @ before connection string. 尝试将@放在连接字符串之前。 We use @ before strings to avoid having to escape special characters. 我们在字符串前使用@,以避免必须转义特殊字符。

string coonection_string =@"Data Source=(LocalDB)  \v11.0;AttachDbFilename=D:\\x\book.mdf;Integrated Security=True;Connect Timeout=30";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM