如何使用App.config将C#与Db连接?

时间:2013-03-12 11:56:39

标签: c# .net sql app-config

我需要使用app.config将SQL#与SQL Server数据库连接。

我的代码是:

public partial class Form1 : Form
{
    string  connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;     

    public Form1()
    {
            InitializeComponent();
    }

    public void InsertDeleteUpdate(string query)
    {
            try
            {
                SqlConnection Conn = new SqlConnection(connectionString);
                Conn.Open();
                SqlCommand comm = new SqlCommand(query, Conn);
                comm.ExecuteNonQuery();
                Conn.Close();
                MessageBox.Show("Succeeded");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

并在app.config我有:

<connectionStrings>
    <add name="Test1" 
         providerName="System.Data.SqlClient"
         connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>

但是我收到了错误,我无法修复它:

  

ConfigurationErrorExeption是Unhandled Configuration系统   无法初始化

有人可以帮我吗?

3 个答案:

答案 0 :(得分:3)

尝试:

var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString; 

您引用Conn作为连接字符串名称,但在Test1

中将其引用为App.Config

答案 1 :(得分:2)

尝试下面的代码然后检查

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

答案 2 :(得分:2)

试试这个..

  <connectionStrings>
  <add name="Conn" providerName="System.Data.SqlClient"
        connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
  </connectionStrings>