首页 > 代码库 > 四个DBHelper实现

四个DBHelper实现

0.



建一个通用的处理数据的类

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Text;  
  5. namespace Document  
  6. {  
  7.     /**//// <summary>  
  8.     /// Summary description for DataHelper.  
  9.     /// </summary>  
  10.     public class DataHelper  
  11.     {  
  12.         public DataHelper()  
  13.         {  
  14.             //  
  15.             // TODO: Add constructor logic here  
  16.             //  
  17.         }  
  18.         public static string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];  
  19.       
  20.         GetDataSet#region GetDataSet  
  21.         public static DataSet GetDataSet(string sql)  
  22.         {  
  23.             SqlDataAdapter    sda =new SqlDataAdapter(sql,ConnectionString);  
  24.             DataSet ds=new DataSet();  
  25.             sda.Fill(ds);  
  26.             return ds;  
  27.         }  
  28.         #endregion  
  29.   
  30.         ExecCommand#region ExecCommand  
  31.         public static int ExecCommand(SqlCommand sqlcom)  
  32.         {  
  33.             SqlConnection conn=new SqlConnection(ConnectionString);  
  34.             sqlcom.Connection =conn;  
  35.             conn.Open();  
  36.             try  
  37.             {  
  38.                 int rtn=sqlcom.ExecuteNonQuery();  
  39.                 return rtn;  
  40.             }  
  41.             catch(Exception ex)   
  42.             {  
  43.                 throw ex;                  
  44.             }  
  45.             finally  
  46.             {  
  47.                 conn.Close();  
  48.             }  
  49.             return 0;  
  50.   
  51.         }  
  52.         public static int ExecCommand(string sql)  
  53.         {  
  54.             if (sql.EndsWith(",")) sql=sql.Substring(0,sql.Length-1);  
  55.           
  56.             SqlCommand sqlcom=new SqlCommand(sql);  
  57.             return ExecCommand(sqlcom);                  
  58.         }  
  59.         #endregion  
  60.           
  61.         ExecuteScalar#region ExecuteScalar  
  62.         public static object ExecuteScalar(string sql)  
  63.         {  
  64.             SqlConnection conn=new SqlConnection(ConnectionString);  
  65.             SqlCommand sqlcom=new SqlCommand(sql,conn);  
  66.             conn.Open();  
  67.             try  
  68.             {  
  69.                 object rtn=sqlcom.ExecuteScalar ();  
  70.                 return rtn;  
  71.             }  
  72.             catch(Exception ex)   
  73.             {  
  74.                 throw ex;                  
  75.             }  
  76.             finally  
  77.             {  
  78.                 conn.Close();  
  79.             }  
  80.             return null;  
  81.         }  
  82.         #endregion  
  83.   
  84.         ExecSPCommand#region ExecSPCommand  
  85.         public static void ExecSPCommand(string sql,System.Data.IDataParameter[] paramers)  
  86.         {  
  87.             SqlConnection conn=new SqlConnection(ConnectionString);  
  88.             SqlCommand sqlcom=new SqlCommand(sql,conn);  
  89.             sqlcom.CommandType= CommandType.StoredProcedure ;  
  90.   
  91.             foreach(System.Data.IDataParameter paramer in paramers)  
  92.             {  
  93.                 sqlcom.Parameters.Add(paramer);  
  94.             }              
  95.             conn.Open();  
  96.             try  
  97.             {  
  98.                 sqlcom.ExecuteNonQuery();  
  99.             }  
  100.             catch(Exception ex)   
  101.             {  
  102.                 string s=ex.Message ;  
  103.             }  
  104.             finally  
  105.             {  
  106.                 conn.Close();  
  107.             }  
  108.         }  
  109.         #endregion  
  110.   
  111.         ExecSPDataSet#region ExecSPDataSet  
  112.         public static DataSet ExecSPDataSet(string sql,System.Data.IDataParameter[] paramers)  
  113.         {  
  114.             SqlConnection conn=new SqlConnection(ConnectionString);  
  115.             SqlCommand sqlcom=new SqlCommand(sql,conn);  
  116.             sqlcom.CommandType= CommandType.StoredProcedure ;  
  117.   
  118.             foreach(System.Data.IDataParameter paramer in paramers)  
  119.             {  
  120.                 sqlcom.Parameters.Add(paramer);  
  121.             }              
  122.             conn.Open();  
  123.               
  124.             SqlDataAdapter da=new SqlDataAdapter();  
  125.             da.SelectCommand=sqlcom;  
  126.             DataSet ds=new DataSet();  
  127.             da.Fill(ds);  
  128.           
  129.             conn.Close();  
  130.             return ds;  
  131.         }  
  132.  
  133.         #endregion  
  134.   
  135.         DbType#region DbType  
  136.         private static System.Data.DbType GetDbType(Type type)  
  137.         {  
  138.             DbType result = DbType.String;  
  139.             if( type.Equals(typeof(int)) ||  type.IsEnum)  
  140.                 result = DbType.Int32;  
  141.             else if( type.Equals(typeof(long)))  
  142.                 result = DbType.Int32;  
  143.             else if( type.Equals(typeof(double)) || type.Equals( typeof(Double)))  
  144.                 result = DbType.Decimal;  
  145.             else if( type.Equals(typeof(DateTime)))  
  146.                 result = DbType.DateTime;  
  147.             else if( type.Equals(typeof(bool)))  
  148.                 result = DbType.Boolean;  
  149.             else if( type.Equals(typeof(string) ) )  
  150.                 result = DbType.String;  
  151.             else if( type.Equals(typeof(decimal)))  
  152.                 result = DbType.Decimal;  
  153.             else if( type.Equals(typeof(byte[])))  
  154.                 result = DbType.Binary;  
  155.             else if( type.Equals(typeof(Guid)))  
  156.                 result = DbType.Guid;  
  157.           
  158.             return result;  
  159.               
  160.         }  
  161.  
  162.         #endregion  
  163.   
  164.         UpdateTable#region UpdateTable  
  165.         public static void UpdateTable(DataTable dt,string TableName,string KeyName)  
  166.         {  
  167.             foreach(DataRow dr in dt.Rows)  
  168.             {  
  169.                 updateRow(dr,TableName,KeyName);  
  170.             }  
  171.         }  
  172.         #endregion  
  173.   
  174.         InsertTable#region InsertTable  
  175.         //用于主键是数据库表名+ID类型的  
  176.         public static void InsertTable(DataTable dt)  
  177.         {  
  178.             string TableName="["+dt.TableName+"]";  
  179.             string KeyName=dt.TableName+"ID";  
  180.             foreach(DataRow dr in dt.Rows)  
  181.             {  
  182.                 insertRow(dr,TableName,KeyName);  
  183.             }  
  184.         }  
  185.         //用于主键是任意类型的  
  186.         public static void InsertTable(DataTable dt,string KeyName)  
  187.         {  
  188.             string TableName="["+dt.TableName+"]";  
  189.             foreach(DataRow dr in dt.Rows)  
  190.             {  
  191.                 insertRow(dr,TableName,KeyName);  
  192.             }  
  193.         }  
  194.         #endregion  
  195.   
  196.         DeleteTable#region DeleteTable  
  197.         public static void DeleteTable(DataTable dt,string KeyName)  
  198.         {  
  199.             string TableName="["+dt.TableName+"]";  
  200.             foreach(DataRow dr in dt.Rows)  
  201.             {  
  202.                 deleteRow(dr,TableName,KeyName);  
  203.             }  
  204.         }  
  205.         #endregion  
  206.   
  207.         updateRow#region updateRow  
  208.         private static void  updateRow(DataRow dr,string TableName,string KeyName)  
  209.         {  
  210.             if (dr[KeyName]==DBNull.Value )   
  211.             {  
  212.                 throw new Exception(KeyName +"的值不能为空");  
  213.             }  
  214.               
  215.             if (dr.RowState ==DataRowState.Deleted)  
  216.             {  
  217.                 deleteRow(dr,TableName,KeyName);  
  218.    
  219.             }  
  220.             else if (dr.RowState ==DataRowState.Modified )  
  221.             {  
  222.                 midifyRow(dr,TableName,KeyName);  
  223.             }  
  224.             else if (dr.RowState ==DataRowState.Added  )  
  225.             {  
  226.                 insertRow(dr,TableName,KeyName);  
  227.             }  
  228.             else if (dr.RowState ==DataRowState.Unchanged )  
  229.             {  
  230.                 midifyRow(dr,TableName,KeyName);  
  231.             }             
  232.         }  
  233.  
  234.         #endregion  
  235.   
  236.         deleteRow#region deleteRow  
  237.         private static void  deleteRow(DataRow dr,string TableName,string KeyName)  
  238.         {  
  239.             string sql="Delete {0} where {1} =@{1}";  
  240.             DataTable dtb=dr.Table ;  
  241.             sql=string.Format(sql,TableName,KeyName);  
  242.   
  243.             SqlCommand sqlcom=new SqlCommand(sql);  
  244.             System.Data.IDataParameter iparam=new  SqlParameter();  
  245.             iparam.ParameterName    = "@"+ KeyName;  
  246.             iparam.DbType            = GetDbType(dtb.Columns[KeyName].DataType);  
  247.             iparam.Value            = dr[KeyName];  
  248.             sqlcom.Parameters .Add(iparam);  
  249.               
  250.             ExecCommand(sqlcom);  
  251.         }  
  252.         #endregion  
  253.   
  254.         midifyRow#region midifyRow  
  255.         private static void  midifyRow(DataRow dr,string TableName,string KeyName)  
  256.         {  
  257.             string UpdateSql            = "Update {0} set {1} {2}";  
  258.             string setSql="{0}= @{0}";  
  259.             string wherSql=" Where {0}=@{0}";  
  260.             StringBuilder setSb    = new StringBuilder();  
  261.   
  262.             SqlCommand sqlcom=new SqlCommand();  
  263.             DataTable dtb=dr.Table;  
  264.           
  265.             for (int k=0; k<dr.Table.Columns.Count; ++k)  
  266.             {  
  267.                 System.Data.IDataParameter iparam=new  SqlParameter();  
  268.                 iparam.ParameterName    = "@"+ dtb.Columns[k].ColumnName;  
  269.                 iparam.DbType            = GetDbType(dtb.Columns[k].DataType);  
  270.                 iparam.Value            = dr[k];  
  271.                 sqlcom.Parameters .Add(iparam);  
  272.   
  273.                 if (dtb.Columns[k].ColumnName==KeyName)  
  274.                 {  
  275.                     wherSql=string.Format(wherSql,KeyName);  
  276.                 }  
  277.                 else  
  278.                 {  
  279.                     setSb.Append(string.Format(setSql,dtb.Columns[k].ColumnName));      
  280.                     setSb.Append(",");  
  281.                 }  
  282.                   
  283.             }  
  284.               
  285.             string setStr=setSb.ToString();  
  286.             setStr=setStr.Substring(0,setStr.Length -1); //trim ,  
  287.               
  288.             string sql = string.Format(UpdateSql, TableName, setStr,wherSql);  
  289.             sqlcom.CommandText =sql;      
  290.             try  
  291.             {  
  292.                 ExecCommand(sqlcom);  
  293.             }  
  294.             catch(Exception ex)  
  295.             {  
  296.                 throw ex;              
  297.             }  
  298.         }  
  299.         #endregion  
  300.   
  301.         insertRow#region insertRow  
  302.         private static void  insertRow(DataRow dr,string TableName,string KeyName)  
  303.         {  
  304.             string InsertSql = "Insert into {0}({1}) values({2})";  
  305.             SqlCommand sqlcom=new SqlCommand();  
  306.             DataTable dtb=dr.Table ;  
  307.             StringBuilder insertValues    = new StringBuilder();  
  308.             StringBuilder cloumn_list    = new StringBuilder();  
  309.             for (int k=0; k<dr.Table.Columns.Count; ++k)  
  310.             {  
  311.                 //just for genentae,  
  312.                 if (dtb.Columns[k].ColumnName==KeyName) continue;  
  313.                 System.Data.IDataParameter iparam=new  SqlParameter();  
  314.                 iparam.ParameterName    = "@"+ dtb.Columns[k].ColumnName;  
  315.                 iparam.DbType            = GetDbType(dtb.Columns[k].DataType);  
  316.                 iparam.Value            = dr[k];  
  317.                 sqlcom.Parameters .Add(iparam);  
  318.   
  319.                 cloumn_list.Append(dtb.Columns[k].ColumnName);  
  320.                 insertValues.Append("@"+dtb.Columns[k].ColumnName);  
  321.   
  322.                 cloumn_list.Append(",");  
  323.                 insertValues.Append(",");  
  324.             }  
  325.               
  326.             string cols=cloumn_list.ToString();  
  327.             cols=cols.Substring(0,cols.Length -1);  
  328.   
  329.             string values=insertValues.ToString();  
  330.             values=values.Substring(0,values.Length -1);  
  331.               
  332.             string sql = string.Format(InsertSql, TableName,cols ,values);  
  333.             sqlcom.CommandText =sql;      
  334.             try  
  335.             {  
  336.                 ExecCommand(sqlcom);  
  337.             }  
  338.             catch(Exception ex)  
  339.             {  
  340.                 throw ex;  
  341.             }  
  342.         }  
  343.         #endregion  
  344.     }  
  345. }