60. C# -- 读取 appconfig文件配置数据库连接的方法

APP.config配置如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings >
    <add name="strCon" connectionString="server=127.0.0.1;user id=root; password=cms1005; database=uestc_infosoft; pooling=false;port=8500"/>
  </connectionStrings>
  <appSettings>
    <add key="ConnectionString" value="server=127.0.0.1;user id=root; password=cms1005; database=uestc_infosoft; pooling=false;port=8500"/>

   <!--add key="ConnectionString" value="Data Source=127.0.0.1;Initial Catalog=uestc_infosoft;Integrated    Security=SSPI;"/-->

    <add key="ConStringEncrypt" value="true"/>
  </appSettings>
</configuration>


主要是数据库操作:

方法一:         string _connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["strCon"].ToString();

 

方法二:                string _connectionString = ConfigurationManager.AppSettings["ConnectionString"];  


在后台读取:
    SqlConnection conn = new SqlConnection();
           conn.ConnectionString = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
           conn.Open();
           string sql = "select * from Orders";
           SqlCommand cmd = new SqlCommand(sql, conn);
           SqlDataAdapter da = new SqlDataAdapter();
           da.SelectCommand = cmd;
           DataSet ds = new DataSet();
           da.Fill(ds);
           this.dataGridView1.DataSource = ds.Tables[0];
           conn.Close();

你可能感兴趣的:(C#)