2013-04-24 39 views
0

我将在Visual Studio 2012(C#)中创建一个SQL Server数据库文件(.MDF文件)。winform应用程序中的SQL Server连接字符串

我工作的桌面应用程序,我添加了一个新的.MDF文件的项目,但我不知道什么是我的连接字符串,我得到这个错误,当我尝试连接到我的DB:

SqlConnection SQLConnection = new SqlConnection("Data Source=db\\ofoghdb.mdf"); 
SQLConnection.Open(); 

错误:

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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

我相当熟悉web开发SQL Server中,但我要在桌面(WinForm的)应用程序来使用它,我得到上述错误

+1

有此错误的几个原因。 http://www.sswug.org/articlesection/default.aspx?TargetID=44331 – 2013-04-24 08:43:05

回答

1

也许你的connectionString想这个?

connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=databaseName;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my.mdf" 
1

尝试指定一个完整的数据库路径:

SqlConnection SQLConnection = new SqlConnection(@"Data Source=C:\ofoghdb.mdf"); 
SQLConnection.Open(); 

查看更多here

+0

我又得到了同样的错误 – 2013-04-24 08:52:58

0

您应该使用这样的连接到数据库服务器:

SqlConnection oSQLConn = new SqlConnection(); 
oSQLConn.ConnectionString = "Data Source=(local);" + 
          "Initial Catalog=mySQLServerDBName;" + 
          "Integrated Security=SSPI"; 
+0

那么m数据库文件名在哪里呢? – 2013-04-24 08:57:07

+0

它是mySQLServerDBName?连接字符串中的 – 2013-04-24 08:59:57

+0

据我所知,我们必须使用dbserver名称而不是.mdf文件名或路径 – AnandPhadke 2013-04-24 09:10:23

0

试试这个连接字符串。

SqlConnection SQLConnection = new SqlConnection(@"Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=DB\MyData.mdf"); 
SQLConnection.Open(); 
0

试试这个

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" 
    + Environment.GetFolderPath(Environment.SpecialFolder.Personal) 
    + "\\folder name\\Databass name " + ";Persist Security Info=False;");