通用数据库连接程序
在做一些数据库应用程序的时候经常遇到动态配置数据库,所以写了一个小程序,利用App.Config动态读写数据库连接字符串,那些还在用Adapter控件的同志们赶紧抛弃吧。
主要实现代码:
代码
using System.Configuration;
using System.Data.OleDb;
//读
string strconn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
//写
private void saveConnection(string connstring)
{
//保存连接
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove("ConnString");
ConnectionStringSettings mySettings = new ConnectionStringSettings("ConnString", connstring, "SQLOLEDB");
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
config.Save(ConfigurationSaveMode.Modified);
// 强制重新载入配置文件的ConnectionStrings配置节
ConfigurationManager.RefreshSection("ConnectionStrings");
}
using System.Data.OleDb;
//读
string strconn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
//写
private void saveConnection(string connstring)
{
//保存连接
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove("ConnString");
ConnectionStringSettings mySettings = new ConnectionStringSettings("ConnString", connstring, "SQLOLEDB");
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
config.Save(ConfigurationSaveMode.Modified);
// 强制重新载入配置文件的ConnectionStrings配置节
ConfigurationManager.RefreshSection("ConnectionStrings");
}