尝试连接到ms sql server时获取实例失败

时间:2012-05-09 16:43:51

标签: .net sql-server ado.net

尝试从c#代码连接到ms sql,但是会收到此错误。如果我像这样建立简单的连接:

  String connect = "server=MY-PC\\SQLEXPRESS; database=mydb; Integrated Security=SSPI;";
          con.ConnectionString = connect;

但是当我从app.config尝试connecto时,我收到了这个错误:

      String connect = ConfigurationManager.AppSettings["connectionString"];
         con.ConnectionString = connect ;

这是xml代码:

    <configuration>
      <appSettings>
       <add key="connectionString" value="server=MY-PC\\SQLEXPRESS; database=mydb;       Integrated        Security=SSPI;"/>
      </appSettings>
     </configuration>

一些想法?

2 个答案:

答案 0 :(得分:0)

您应该在app.config中设置连接字符串,如下所示

<connectionStrings>
<add name="connect" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated 
Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

然后将连接字符串作为

ConfigurationManager.ConnectionStrings["connect"].ConnectionString

示例Conn字符串:

<add name="NorthWind" 
       providerName="System.Data.SqlClient" 
       connectionString="server=.;database=NorthWind;Integrated Security=SSPI" />

答案 1 :(得分:0)

试试这个

String connect = @“Data Source =。\ SQLEXPRESS; AttachDbFilename = mydb; Integrated Security = True;”               con.ConnectionString = connect;