在Web.config中配置数据库连接(利用抽象工厂方便更换数据库)
(一). 在网站的Web.config文件中配置数据库的连接信息是有很多好处的,可以很方便的更换其他数据库(MSSQL,ORACAL,ACCESS,MYSQL...),据说还可以方便MS加密,还有方便直接将数据源绑定到控件上而不必写代码。这里将2种配置方法及如何获取配置的连接信息的方法列出来,以备后用。
1. 在<connectionStrings>中配置
<connectionStrings> <add name="DBConnection" connectionString="server=T3-IT03\SQLEXPRESS;uid=sa;password=sa;database=test" providerName="System.Data.SqlClient" /> </connectionStrings>
获取connectionString,和ProviderName的方法是:
string connStr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; string provider = ConfigurationManager.ConnectionStrings["DBConnection"].ProviderName;
2. 在<appSettings>中配置
<appSettings> <add key="DBConnection" value="server=T3-IT03\SQLEXPRESS;uid=sa;password=sa;database=test"/> </appSettings>
获取connectionString的方法是:
string connStr = ConfigurationManager.AppSettings["DBConnection"];
(二). 利用抽象工厂创建基于配置的数据库Provider的数据库连接Connection,Adapter,Command等
首先引用命名空间
using System.Data.Common;
利用工厂创建Connection,Adapter范例:
string connString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; string provider = ConfigurationManager.ConnectionStrings["DBConnection"].ProviderName; DbProviderFactory factory = DbProviderFactories.GetFactory(provider); DbConnection conn = factory.CreateConnection(); conn.ConnectionString = connString; DbDataAdapter adapter = factory.CreateDataAdapter(); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from Book"; adapter.SelectCommand = cmd; DataSet set = new DataSet(); adapter.Fill(set);