如何在app.config文件中提供连接字符串以及如何调用它

时间:2013-01-02 13:04:07

标签: c# connection-string

我在app.config中使用了以下代码

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=162.1.6.4;Initial Catalog=Followon_SP;Integrated Security=SSPI" 
     providerName="System.Data.SqlClient"/>

和form.cs

struct st
{

    public static SqlConnection con;
};
public Mainform()
    {
        InitializeComponent();           
       st.con = new SqlConnection( ConfigurationManager.AppSettings["Connectionstring"].ToString());
    }

但是我在连接打开时遇到以下错误,

4 个答案:

答案 0 :(得分:2)

你需要改用它:

public Mainform()
{
    InitializeComponent();     

    // read out the .ConnectionString property - don't call .ToString() !!
    string cs = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
    st.con = new SqlConnection(cs);
}

使用ConfigurationManager.ConnectionStrings(而不是ConfigurationManager.AppSettings),然后从.ConnectionString属性中读取连接字符串,而不是在其上调用.ToString()

答案 1 :(得分:0)

将新SqlConnection(cs)设置为con字段的结构类型。像这样使用它;

string cs = ConfigurationManager.AppSettings["Connectionstring"].ConnectionString;
st.con = new SqlConnection(cs);

答案 2 :(得分:0)

使用实体框架会更好:http://msdn.microsoft.com/en-us/data/ef.aspx

添加新的数据模型,只要您拥有在向导中输入的正确用户名和密码,VS就会处理您的所有配置设置。将使您的开发过程更加轻松。

答案 3 :(得分:0)

使用以下代码读取连接字符串:

System.Configuration.Configuration rootWebConfig = 
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) {
    connString =
        rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    if (connString != null)
        Console.WriteLine("Northwind connection string = \"{0}\"", connString.ConnectionString);
    else
        Console.WriteLine("No Northwind connection string");
}