使用App.config管理数据库连接

程序的数据库连接字符串可以保持在程序的配置文件App.config中,便于管理。

将配置文件添加至解决方案:

添加连接信息:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Odbc" providerName="System.Data.Odbc" connectionString="Driver={Microsoft Access Driver (*.mdb)};DBQ= F:\\1.mdb;"/>
    <add name="Oracle" providerName="System.Data.OracleClient" connectionString="Data Source = orcl;User Id= aqgis;Password= 1;"/>
  </connectionStrings>
</configuration>

通过连接名称获取DbConnection函数:

/// <summary>
        /// 通过连接名称获取DbConnection
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private System.Data.Common.DbConnection GetDbConnection(string name)
        {
            System.Configuration.ConnectionStringSettings settings = 
                System.Configuration.ConfigurationManager.ConnectionStrings[name];
            System.Data.Common.DbProviderFactory factory =
                System.Data.Common.DbProviderFactories.GetFactory(settings.ProviderName);
            System.Data.Common.DbConnection conn = factory.CreateConnection();
            conn.ConnectionString = settings.ConnectionString;
            return conn;
        }

连接测试:

System.Data.Common.DbConnection conn1 = GetDbConnection("Odbc");
            System.Data.Common.DbConnection conn2 = GetDbConnection("Oracle");
            conn1.Open();
            conn2.Open();

            //***do something

            conn1.Close();
            conn2.Close();

 

posted @ 2016-12-22 15:02  Hxxxxxxyyyyyy  阅读(2968)  评论(0编辑  收藏  举报