通过改变配置文件实现访问不同数据库的工厂模式。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using
System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Common;
public partial class DataBaseFactory : System.Web.UI.Page
{
private DbConnection con;
private DbCommand cmd;
private DbProviderFactory provider;
public DataBaseFactory()
{
string providerName = ConfigurationManager.ConnectionStrings[ 1 ].ProviderName;
provider = DbProviderFactories.GetFactory(providerName);
con = provider.CreateConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings[ 1 ].ConnectionString;
cmd = provider.CreateCommand();
cmd.Connection = con;
}
public DataTable getAlarmTable( string sql)
{
if (con != null )
{
try
{
DataSet ds = new DataSet();
DbDataAdapter da = provider.CreateDataAdapter(sql, con);
da.Fill(ds);
da.Dispose();
return ds.Tables[ 0 ];
}
catch (Exception e)
{
// 2010.01.26 注释打印信息,添加Log日志。
Program.WriteLog(e.Message.ToString());
// Console.WriteLine(e.Message);
return null ;
}
finally
{
if (con != null )
{
con.Close();
}
}
}
else
{
Console.WriteLine(DateTime.Now.ToString() + " 没有连接到数据库 " );
return null ;
}
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Common;
public partial class DataBaseFactory : System.Web.UI.Page
{
private DbConnection con;
private DbCommand cmd;
private DbProviderFactory provider;
public DataBaseFactory()
{
string providerName = ConfigurationManager.ConnectionStrings[ 1 ].ProviderName;
provider = DbProviderFactories.GetFactory(providerName);
con = provider.CreateConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings[ 1 ].ConnectionString;
cmd = provider.CreateCommand();
cmd.Connection = con;
}
public DataTable getAlarmTable( string sql)
{
if (con != null )
{
try
{
DataSet ds = new DataSet();
DbDataAdapter da = provider.CreateDataAdapter(sql, con);
da.Fill(ds);
da.Dispose();
return ds.Tables[ 0 ];
}
catch (Exception e)
{
// 2010.01.26 注释打印信息,添加Log日志。
Program.WriteLog(e.Message.ToString());
// Console.WriteLine(e.Message);
return null ;
}
finally
{
if (con != null )
{
con.Close();
}
}
}
else
{
Console.WriteLine(DateTime.Now.ToString() + " 没有连接到数据库 " );
return null ;
}
}
}