如何将连接字符串作为键值?

时间:2012-11-06 00:03:44

标签: c# asp.net

我想将连接字符串作为键。 所以我在web.config中写了这段代码。

    <add key="connectstring" value="Data Source=USER-PC;Initial Catalog=DBName; Integrated Security=False; providerName=System.Data.SqlClient"/>
  </appSettings>

但是有错误,它说

Keyword not supported: 'providername'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Keyword not supported: 'providername'.

Source Error:

Line 28:             SqlConnection conn;
Line 29:             conn = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
Line 30:                 
Line 31: 

我该如何解决?

2 个答案:

答案 0 :(得分:1)

尝试使用ConfigurationManager对象:

string connectionString 
    = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

<connectionStrings>
    <remove name="LocalSqlServer" />
    <add name="LocalSqlServer" 
        connectionString="Initial Catalog=MyDB;Data Source=MyPC;Integrated Security=SSPI;"
            providerName="System.Data.SqlClient" />
<connectionStrings>

使用appSettings:

System.Configuration.ConfigurationManager.Appsettings.Get("connectstring");

答案 1 :(得分:1)

<appSettings>
<add key="connectstring" value="Data Source=USER-PC;Initial Catalog=DBName; Integrated Security=False;" providerName="System.Data.SqlClient"/>

在您的值中分隔 providerName

注意:您的值存在错误,请在 错误后添加双重qoutation;