.NET数据库工厂模式简单实现

通过改变配置文件实现访问不同数据库的工厂模式。

代码
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 ;
        }
    }   
}

 

 

你可能感兴趣的:(.net)