通用数据库操作辅助类DbHelper

http://www.cnblogs.com/yelaiju/archive/2010/09/22/1832916.html

 

使用方式
DbHelper db;
OpenFileDialog ofd 
=   new  OpenFileDialog();
ofd.Filter 
=   " SQLite数据文件(*.db3;*.db;*.sqlite)|*.db3;*.db;*.sqlite " ;
if  (ofd.ShowDialog()  ==  DialogResult.OK)
{
    txtDataSource.Text 
=  ofd.FileName;
    db 
=   new  DbHelper( " data source= "   +  txtDataSource.Text, DbProvider.Sqlite);
}
db.ReExNum(txtSql.Text); 

接口
using  System.Data;
using  System.Collections.Generic;
using  System.Data.Common;

///  


///  该类用于对数据库进行操作
///  Design by 火地晋
///  

namespace  System.Data
{
    
public   interface  IDbObject
    {
        
///  
        
///  定义一个DataReader的列表,已备检索
        
///  

        List < DbDataReader >  DataReaderList {  get set ; }
        
///  
        
///  
        
///  

        DbConnection Connection {  get set ; }
        
string  ConnectionString {  get set ; }
        DbProvider DbProviderType { 
get set ; }
        
        
///  
        
///  返回执行操作成功的数目,使用注意,如果是存储过程,必须在存储过程后加上:select @@ROWCOUNT
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         int  ReExNum( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  返回结果的存储过程
        
///  

        
///   任何SQL语句
        
///   参数值
        
///  
        DbDataReader ReSelectdr( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  返回dateSet
        
///  

        
///  
        
///  
        
///  
        
///  
        DataSet ReSelectds( string  strSql,  string  tableName,  params  DbParameter[] parameters);
        DataTable ReSelectdtb(
string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  通過存儲過程及自定義參數組查詢返回SqlDataAdapter對象
        
///  

        DbDataAdapter ReSelectdat( string  strSql,  params  DbParameter[] parameters);

        
void  ExSQL( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///      執行SQL查詢語句,返回記錄條數
        
///  

        
///   Select語句(在select语句中,使用Count(*)函数)
        
///   返回查詢到之記錄條數
         int  ReSelectNum( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  使用SqlDataAdapter返回指定范围的数据
        
///  

        
///   存储过程名
        
///   参数名
        
///   起始行
        
///   记录数
        
///   表名
        
///  
        DataSet ReSelectds( string  strSql, DbParameter[] parameters,  int  start,  int  maxRecord,  string  tableName);
        
///  
        
///  返回执行操作成功的数目,不关闭连接
        
///  

        
///   执行的查询语句或存储过程
        
///   参数组
        
///  
         int  ReExNumNoClose( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  返回执行操作成功的数目,不关闭连接,并返回出现的错误信息。
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         int  ReExNumNoClose( string  strSql,  out   string  error,  params  DbParameter[] parameters);

        
///  
        
///  返回执行操作成功的数目,并返回发生的错误信息
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         int  ReExNum( string  strSql,  out   string  error,  params  DbParameter[] parameters);

        
///  
        
///  返回执行操作结果的信息,如果返回为空则表示没错误,否则返回错误的信息。
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         string  ReExStr( string  strSql,  params  DbParameter[] parameters);
        
///  
        
///  如果数据库连接已关闭,则打开
        
///  

        
///  
         bool  OpenConnection();
        
///  
        
///  关闭数据库连接
        
///  

         void  CloseConnection();
    }
    
public   enum  DbProvider
    {
        Sql
= 0 ,
        Sqlite
= 1 ,
        OleDb
= 2 ,
        Oracle
= 3 ,
        MySql
= 4
    }
}
 

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Data.Common;

namespace  System.Data
{
    
public   class  DbHelper : IDbObject
    {
        
#region  属性
        
public  List < DbDataReader >  DataReaderList {  get set ; }
        
public  DbConnection Connection {  get set ; }
        
public   string  ConnectionString {  get set ; }
        
public  DbProvider DbProviderType {  get set ; }
        
private  DbProviderFactory dbFactory;
        
#endregion

        
#region  构造函数
        
public  DbHelper()
        {
            DbHelperInstance(System.Configuration.ConfigurationManager.AppSettings[
" ConnectionString " ], DbProvider.Sql);
        }
        
public  DbHelper( string  connectionString)
        {
            DbHelperInstance(connectionString, DbProvider.Sql);
        }
        
public  DbHelper(DbProvider dbProviderType)
        {
            DbHelperInstance(System.Configuration.ConfigurationManager.AppSettings[
" ConnectionString " ], dbProviderType);
        }
        
public  DbHelper( string  connectionString, DbProvider dbProviderType)
        {
            DbHelperInstance(connectionString, dbProviderType);
        }
        
///  
        
///  初始化
        
///  

        
///  
        
///  
         public   void  DbHelperInstance( string  connectionString, DbProvider dbProviderType)
        {
            
this .DbProviderType  =  dbProviderType;
            
this .ConnectionString  =  connectionString;
            DataReaderList 
=   new  List < DbDataReader > ();
            CreateFactory();
            
this .Connection  =   this .dbFactory.CreateConnection();
            
this .Connection.ConnectionString  =   this .ConnectionString;
        }
        
#endregion
        
///  
        
///  创建数据操作工厂
        
///  

         private   void  CreateFactory()
        {
            
switch  (DbProviderType)
            {
                
case  DbProvider.Sql:
                    
this .dbFactory  =  System.Data.SqlClient.SqlClientFactory.Instance;
                    
break ;
                
case  DbProvider.Sqlite:
                    
this .dbFactory  =  System.Data.SQLite.SQLiteFactory.Instance;
                    
break ;
                
case  DbProvider.OleDb:
                    
this .dbFactory  =  System.Data.OleDb.OleDbFactory.Instance;
                    
break ;
                
case  DbProvider.Oracle:
                    
this .dbFactory  =  System.Data.OracleClient.OracleClientFactory.Instance;
                    
break ;
                
case  DbProvider.MySql:
                    
this .dbFactory  =  MySql.Data.MySqlClient.MySqlClientFactory.Instance;
                    
break ;
            }
        }
        
///  
        
///  创建操作对象
        
///  

        
///   如果包含@,则采用CommandType.Text
        
///  
        
///  
         private  DbCommand BuilderQueryCommand( string  procNameOrExText,  params  DbParameter[] parameters)
        {
            
if  (parameters  ==   null   ||  parameters.Length  ==   0 )
            {
                DbCommand command 
=   this .dbFactory.CreateCommand();
                command.CommandText 
=  procNameOrExText;
                command.Connection 
=   this .Connection;
                
return  command;
            }
            
if  (procNameOrExText.IndexOf( ' @ ' >   0 ) // 存储过程
            {
                
return  BuilderQueryCommandText(procNameOrExText, parameters);
            }
            
else
            {
                
return  BuilderQueryCommandStorPro(procNameOrExText, parameters);
            }
        }

        
///  
        
///  根据存储过程名称和参数生成对应的SQL命令对象
        
///  

        
///   存储过程名或者
        
///   存储过程参数
        
///  
         private  DbCommand BuilderQueryCommandStorPro( string  strSql,  params  DbParameter[] parameters)
        {
            DbCommand command 
=   this .dbFactory.CreateCommand();
            command.CommandText 
=  strSql;
            command.CommandType 
=  CommandType.StoredProcedure;
            command.Connection 
=   this .Connection;
            
if  (parameters  !=   null )
            {
                
foreach  (DbParameter p  in  parameters)
                {
                    command.Parameters.Add(p);
                }
            }
            
return  command;
        }
        
private  DbCommand BuilderQueryCommandText( string  strSql,  params  DbParameter[] parameters)
        {
            DbCommand command 
=   this .dbFactory.CreateCommand();
            command.CommandText 
=  strSql;
            command.Connection 
=   this .Connection;
            
if  (parameters  !=   null )
            {
                
foreach  (DbParameter p  in  parameters)
                {
                    command.Parameters.Add(p);
                }
            }
            
return  command;
        }
        
public  DbParameter CreateDbParameter( string  parameterName)
        {
            
return  CreateDbParameter(parameterName, DBNull.Value, DbType.Object,  0 , ParameterDirection.Input);
        }
        
public  DbParameter CreateDbParameter( string  parameterName,  object  value)
        {
            
return  CreateDbParameter(parameterName, value, DbType.Object,  0 , ParameterDirection.Input);
        }
        
public  DbParameter CreateDbParameter( string  parameterName,  object  value, DbType dbType)
        {
            
return  CreateDbParameter(parameterName,value,dbType, 0 ,ParameterDirection.Input);
        }
        
public  DbParameter CreateDbParameter( string  parameterName,  object  value, DbType dbType,  int  size)
        {
            
return  CreateDbParameter(parameterName,value,dbType,size,ParameterDirection.Input);
        }
        
public  DbParameter CreateDbParameter( string  parameterName,  object  value, DbType dbType,  int  size, ParameterDirection parameterDirection)
        {
            DbParameter pat 
=   this .dbFactory.CreateParameter();
            pat.ParameterName 
=  parameterName;
            pat.Value 
=  value;
            pat.DbType 
=  dbType;
            pat.Size 
=  size;
            pat.Direction 
=  parameterDirection;
            
return  pat;
        }
        
///  
        
///  返回执行操作成功的数目,使用注意,如果是存储过程,必须在存储过程后加上:select @@ROWCOUNT
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         public   int  ReExNum( string  strSql,  params  DbParameter[] parameters)
        {
            
int  effect  =   0 ;
            
if  ( ! OpenConnection())  return   - 1 ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                
// 根据是否为存储过程来执行不同的处理
                 if  (cmd.CommandType  ==  CommandType.StoredProcedure)
                {
                    
object  result  =  cmd.ExecuteScalar();
                    effect 
=  result  ==   null   ?   - 1  : Convert.ToInt16(result);
                }
                
else
                {
                    effect 
=  cmd.ExecuteNonQuery();
                }
                trans.Commit();
                
return  effect;
            }
            
catch
            {
                trans.Rollback();
                Connection.Close();
                
return   - 1 ;
            }
            
finally
            {
                Connection.Close();
            }
        }
        
///  
        
///  返回结果的存储过程
        
///  

        
///   任何SQL语句
        
///   参数值
        
///  
         public  DbDataReader ReSelectdr( string  strSql,  params  DbParameter[] parameters)
        {
            
try
            {
                DbDataReader reader;
                
if  ( ! OpenConnection())  return   null ;
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                reader 
=  cmd.ExecuteReader(CommandBehavior.CloseConnection); // 在dr关闭之后,就不需要进行cnn的关闭操作了
                DataReaderList.Add(reader); // 添加进dr列表,已备检索
                 return  reader;
            }
            
catch
            {
                
return   null ;
            }
        }
        
///  
        
///  返回dateSet
        
///  

        
///  
        
///  
        
///  
        
///  
         public  DataSet ReSelectds( string  strSql,  string  tableName,  params  DbParameter[] parameters)
        {
            
try
            {
                DataSet ds 
=   new  DataSet();
                
if  ( ! OpenConnection())  return   null ;
                DbDataAdapter myDa 
=   this .dbFactory.CreateDataAdapter();
                myDa.SelectCommand 
=  BuilderQueryCommand(strSql, parameters);
                myDa.Fill(ds, tableName);
                
return  ds;
            }
            
catch
            {
                
return   null ;
            }
            
finally
            {
                Connection.Close();
            }
        }
        
public  DataTable ReSelectdtb( string  strSql,  params  DbParameter[] parameters)
        {
            
try
            {
                DataTable dt 
=   new  DataTable();
                
if  ( ! OpenConnection())  return   null ;
                DbDataAdapter myDa 
=   this .dbFactory.CreateDataAdapter();
                myDa.SelectCommand 
=  BuilderQueryCommand(strSql, parameters);
                myDa.Fill(dt);
                
return  dt;
            }
            
catch
            {
                
return   null ;
            }
            
finally
            {
                Connection.Close();
            }
        }
        
///  
        
///  通過存儲過程及自定義參數組查詢返回SqlDataAdapter對象
        
///  

         public  DbDataAdapter ReSelectdat( string  strSql,  params  DbParameter[] parameters)
        {
            
if  ( ! OpenConnection())  return   null ;
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                DbDataAdapter myDa 
=   this .dbFactory.CreateDataAdapter();
                myDa.SelectCommand 
=  cmd;
                
return  myDa;
            }
            
catch
            {
                Connection.Close();
                
return   null ;
            }
        }

        
public   void  ExSQL( string  strSql,  params  DbParameter[] parameters)
        {
            
if  ( ! OpenConnection())  return ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                cmd.ExecuteNonQuery();
                trans.Commit();
            }
            
catch
            {
                trans.Rollback();
                Connection.Close();
                
return ;
            }
            
finally
            {
                Connection.Close();
            }
        }
        
///  
        
///   執行SQL查詢語句,返回記錄條數
        
///  

        
///   Select語句(在select语句中,使用Count(*)函数)
        
///   返回查詢到之記錄條數
         public   int  ReSelectNum( string  strSql,  params  DbParameter[] parameters)
        {
            
int  effect  =   0 ;
            
try
            {
                DbDataReader dr 
=  ReSelectdr(strSql, parameters);
                
if  (dr.Read())
                {
                    effect 
=  Convert.ToInt32(dr.GetValue( 0 ));
                }
                
return  effect;
            }
            
catch
            {
                
return  effect;

            }
        }
        
///  
        
///  使用SqlDataAdapter返回指定范围的数据
        
///  

        
///   存储过程名
        
///   参数名
        
///   起始行
        
///   记录数
        
///   表名
        
///  
         public  DataSet ReSelectds( string  strSql, DbParameter[] parameters,  int  start,  int  maxRecord,  string  tableName)
        {
            
try
            {
                DataSet ds 
=   new  DataSet();
                OpenConnection();
                DbDataAdapter myDa 
=   this .dbFactory.CreateDataAdapter();
                myDa.SelectCommand 
=  BuilderQueryCommand(strSql, parameters);
                myDa.Fill(ds, start, maxRecord, tableName);
                
return  ds;
            }
            
catch
            {
                Connection.Close();
                
return   null ;
            }
            
finally
            {
                Connection.Close();
            }
        }
        
///  
        
///  返回执行操作成功的数目,不关闭连接
        
///  

        
///   执行的查询语句或存储过程
        
///   参数组
        
///  
         public   int  ReExNumNoClose( string  strSql,  params  DbParameter[] parameters)
        {
            
int  effect  =   0 ;
            
if  ( ! OpenConnection())  return   - 1 ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                
// 根据是否为存储过程来执行不同的处理
                 if  (cmd.CommandType  ==  CommandType.StoredProcedure)
                {
                    
object  result  =  cmd.ExecuteScalar();
                    effect 
=  result  ==   null   ?   - 1  : Convert.ToInt16(result);
                }
                
else
                {
                    effect 
=  cmd.ExecuteNonQuery();
                }
                trans.Commit();
                
return  effect;
            }
            
catch
            {
                trans.Rollback();
                
return  effect;
            }
        }
        
///  
        
///  返回执行操作成功的数目,不关闭连接,并返回出现的错误信息。
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         public   int  ReExNumNoClose( string  strSql,  out   string  error,  params  DbParameter[] parameters)
        {
            
int  effect  =   0 ;
            error 
=   "" ;
            
if  ( ! OpenConnection())  return   - 1 ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                
if  (cmd.CommandType  ==  CommandType.StoredProcedure)
                {
                    
object  result  =  cmd.ExecuteScalar();
                    effect 
=  result  ==   null   ?   - 1  : Convert.ToInt16(result);
                }
                
else
                {
                    effect 
=  cmd.ExecuteNonQuery();
                }
                effect 
=  cmd.ExecuteNonQuery();
                trans.Commit();
                
return  effect;
            }
            
catch  (Exception ex)
            {
                trans.Rollback();
                error 
=  ex.Message;
                
return  effect;
            }
        }

        
///  
        
///  返回执行操作成功的数目,并返回发生的错误信息
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         public   int  ReExNum( string  strSql,  out   string  error,  params  DbParameter[] parameters)
        {
            
int  effect  =   0 ;
            error 
=   "" ;
            
if  ( ! OpenConnection())  return   - 1 ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                
if  (cmd.CommandType  ==  CommandType.StoredProcedure)
                {
                    
object  result  =  cmd.ExecuteScalar();
                    effect 
=  result  ==   null   ?   - 1  : Convert.ToInt16(result);
                }
                
else
                {
                    effect 
=  cmd.ExecuteNonQuery();
                }
                trans.Commit();
                
return  effect;
            }
            
catch  (Exception ex)
            {
                trans.Rollback();
                error 
=  ex.Message;
                
return  effect;
            }
            
finally
            {
                Connection.Close();
            }
        }

        
///  
        
///  返回执行操作结果的信息,如果返回为空则表示没错误,否则返回错误的信息。
        
///  

        
///   存储过程名
        
///   参数组
        
///  
         public   string  ReExStr( string  strSql,  params  DbParameter[] parameters)
        {
            
string  error  =   string .Empty;
            
int  effect  =   0 ;
            
if  ( ! OpenConnection())  return   null ;
            DbTransaction trans 
=  Connection.BeginTransaction();
            
try
            {
                DbCommand cmd 
=  BuilderQueryCommand(strSql, parameters);
                cmd.Transaction 
=  trans;
                effect 
=  cmd.ExecuteNonQuery();
                trans.Commit();
                
if  (effect  ==   0 )
                {
                    error 
=   " 操作成功记录数为0,请检查意外的错误。 "   +   "  sql语句: "   +  strSql;
                }
                
else
                {
                    error 
=   "" ;
                }
            }
            
catch  (Exception ex)
            {
                trans.Rollback();
                error 
=   " sql语句: "   +  strSql  +   "  错误信息: "   +  ex.Message;
            }
            
finally
            {
                Connection.Close();
            }
            
return  error;
        }
        
///  
        
///  如果数据库连接已关闭,则打开
        
///  

        
///  
         public   bool  OpenConnection()
        {
            
if  (Connection.State  ==  ConnectionState.Closed)
            {
                
try
                {
                    Connection.Open();
                }
                
catch
                {
                    
return   false ;
                }
            }
            
return   true ;
        }
        
public   void  CloseConnection()
        {
            Connection.Close();
        }
    }
}


 

你可能感兴趣的:(C#,数据库,parameters,存储,sql,sqlite,null)