程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#全能數據庫操作類及調用示例

C#全能數據庫操作類及調用示例

編輯:C#入門知識

[csharp]
using System; 
using System.Data; 
using System.Data.Common; 
using System.Configuration; 
namespace MSCL 

    ///

  
    /// DbHelper通用數據庫類  
    ///
  
    public class DbHelper 
    { 
        ///   
        ///   
        ///
  
        private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"]; 
 
        ///   
        ///   
        ///
  
        private static string dbConnectionString = ConfigurationManager.AppSettings["ConnectionString"]; 
 
        private DbConnection connection; 
        public DbHelper() 
        { 
            this.connection = CreateConnection(DbHelper.dbConnectionString); 
        } 
        public DbHelper(string connectionString) 
        { 
            this.connection = CreateConnection(connectionString); 
        } 
        public static DbConnection CreateConnection() 
        { 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbConnection dbconn = dbfactory.CreateConnection(); 
            dbconn.ConnectionString = DbHelper.dbConnectionString; 
            return dbconn; 
        } 
        public static DbConnection CreateConnection(string connectionString) 
        { 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbConnection dbconn = dbfactory.CreateConnection(); 
            dbconn.ConnectionString = connectionString; 
            return dbconn; 
        } 
 
        ///   
        /// 執行存儲過程  
        ///
  
        ///存儲過程名  
        ///   
        public DbCommand GetStoredProcCommand(string storedProcedure) 
        { 
            DbCommand dbCommand = connection.CreateCommand(); 
            dbCommand.CommandText = storedProcedure; 
            dbCommand.CommandType = CommandType.StoredProcedure; 
            return dbCommand; 
        } 
 
        ///   
        /// 執行SQL語句  
        ///
  
        ///SQL語句  
        ///   
        public DbCommand GetSqlStringCommand(string sqlQuery) 
        { 
            DbCommand dbCommand = connection.CreateCommand(); 
            dbCommand.CommandText = sqlQuery; 
            dbCommand.CommandType = CommandType.Text; 
            return dbCommand; 
        } 
 
        #region 增加參數  
 
        public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection) 
        { 
            foreach (DbParameter dbParameter in dbParameterCollection) 
            { 
                cmd.Parameters.Add(dbParameter); 
            } 
        } 
 
        ///   
        /// 增加輸出參數  
        ///
  
        ///  
        ///  
        ///  
        ///  
        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size) 
        { 
            DbParameter dbParameter = cmd.CreateParameter(); 
            dbParameter.DbType = dbType; 
            dbParameter.ParameterName = parameterName; 
            dbParameter.Size = size; 
            dbParameter.Direction = ParameterDirection.Output; 
            cmd.Parameters.Add(dbParameter); 
        } 
 
        ///   
        /// 增加輸入參數  
        ///
  
        ///  
        ///  
        ///  
        ///  
        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value) 
        { 
            DbParameter dbParameter = cmd.CreateParameter(); 
            dbParameter.DbType = dbType; 
            dbParameter.ParameterName = parameterName; 
            dbParameter.Value = value; 
            dbParameter.Direction = ParameterDirection.Input; 
            cmd.Parameters.Add(dbParameter); 
        } 
 
        ///   
        /// 增加返回參數  
        ///
  
        ///  
        ///  
        ///  
        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType) 
        { 
            DbParameter dbParameter = cmd.CreateParameter(); 
            dbParameter.DbType = dbType; 
            dbParameter.ParameterName = parameterName; 
            dbParameter.Direction = ParameterDirection.ReturnValue; 
            cmd.Parameters.Add(dbParameter); 
        } 
 
        public DbParameter GetParameter(DbCommand cmd, string parameterName) 
        { 
            return cmd.Parameters[parameterName]; 
        } 
 
        #endregion 
 
        #region 執行  
 
        ///   
        /// 執行查詢返回DataSet  
        ///
  
        ///  
        ///   
        public DataSet ExecuteDataSet(DbCommand cmd) 
        { 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter(); 
            dbDataAdapter.SelectCommand = cmd; 
            DataSet ds = new DataSet(); 
            dbDataAdapter.Fill(ds); 
            return ds; 
        } 
 
        ///   
        /// 執行查詢返回DataTable  
        ///
  
        ///  
        ///   
        public DataTable ExecuteDataTable(DbCommand cmd) 
        { 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter(); 
            dbDataAdapter.SelectCommand = cmd; 
            DataTable dataTable = new DataTable(); 
            dbDataAdapter.Fill(dataTable); 
            return dataTable; 
        } 
 
        ///   
        /// 執行查詢返回DataReader  
        ///
  
        ///  
        ///   
        public DbDataReader ExecuteReader(DbCommand cmd) 
        { 
            cmd.Connection.Open(); 
            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
            return reader; 
        } 
 
        ///   
        /// 執行SQL語句,返回影響行數  
        ///
  
        ///  
        ///   
        public int ExecuteNonQuery(DbCommand cmd) 
        { 
            cmd.Connection.Open(); 
            int ret = cmd.ExecuteNonQuery(); 
            cmd.Connection.Close(); 
            return ret; 
        } 
 
        ///   
        /// 返回首行首列對象  
        ///
  
        ///  
        ///   
        public object ExecuteScalar(DbCommand cmd) 
        { 
            cmd.Connection.Open(); 
            object ret = cmd.ExecuteScalar(); 
            cmd.Connection.Close(); 
            return ret; 
        } 
        #endregion 
 
        #region 執行事務  
 
        ///   
        /// 執行事務返回DataSet  
        ///
  
        ///  
        ///  
        ///   
        public DataSet ExecuteDataSet(DbCommand cmd, Trans t) 
        { 
            cmd.Connection = t.DbConnection; 
            cmd.Transaction = t.DbTrans; 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter(); 
            dbDataAdapter.SelectCommand = cmd; 
            DataSet ds = new DataSet(); 
            dbDataAdapter.Fill(ds); 
            return ds; 
        } 
 
        ///   
        /// 執行事務返回DataTable  
        ///
  
        ///  
        ///  
        ///   
        public DataTable ExecuteDataTable(DbCommand cmd, Trans t) 
        { 
            cmd.Connection = t.DbConnection; 
            cmd.Transaction = t.DbTrans; 
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName); 
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter(); 
            dbDataAdapter.SelectCommand = cmd; 
            DataTable dataTable = new DataTable(); 
            dbDataAdapter.Fill(dataTable); 
            return dataTable; 
        } 
 
        ///   
        /// 執行事務返回DataReader  
        ///
  
        ///  
        ///  
        ///   
        public DbDataReader ExecuteReader(DbCommand cmd, Trans t) 
        { 
            cmd.Connection.Close(); 
            cmd.Connection = t.DbConnection; 
            cmd.Transaction = t.DbTrans; 
            DbDataReader reader = cmd.ExecuteReader(); 
            return reader; 
        } 
 
        ///   
        /// 執行事務SQL語句返回影響行數  
        ///
  
        ///  
        ///  
        ///   
        public int ExecuteNonQuery(DbCommand cmd, Trans t) 
        { 
            cmd.Connection.Close(); 
            cmd.Connection = t.DbConnection; 
            cmd.Transaction = t.DbTrans; 
            int ret = cmd.ExecuteNonQuery(); 
            return ret; 
        } 
 
        ///   
        /// 執行事務SQL語句返回首行首列  
        ///
  
        ///  
        ///  
        ///   
        public object ExecuteScalar(DbCommand cmd, Trans t) 
        { 
            cmd.Connection.Close(); 
            cmd.Connection = t.DbConnection; 
            cmd.Transaction = t.DbTrans; 
            object ret = cmd.ExecuteScalar(); 
            return ret; 
        } 
        #endregion  
    } 
 
    public class Trans : IDisposable 
    { 
        private DbConnection conn; 
        private DbTransaction dbTrans; 
        public DbConnection DbConnection 
        { 
            get { return this.conn; } 
        } 
        public DbTransaction DbTrans 
        { 
            get { return this.dbTrans; } 
        } 
 
        public Trans() 
        { 
            conn = DbHelper.CreateConnection(); 
            conn.Open(); 
            dbTrans = conn.BeginTransaction(); 
        } 
        public Trans(string connectionString) 
        { 
            conn = DbHelper.CreateConnection(connectionString); 
            conn.Open(); 
            dbTrans = conn.BeginTransaction(); 
        } 
        public void Commit() 
        { 
            dbTrans.Commit(); 
            this.Colse(); 
        } 
 
        public void RollBack() 
        { 
            dbTrans.Rollback(); 
            this.Colse(); 
        } 
 
        public void Dispose() 
        { 
            this.Colse(); 
        } 
 
        public void Colse() 
        { 
            if (conn.State == System.Data.ConnectionState.Open) 
            { 
                conn.Close(); 
            } 
        } 
    } 

 

using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
namespace MSCL
{
    ///


    /// DbHelper通用數據庫類
    ///

    public class DbHelper
    {
        ///
        ///
        ///

        private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];

 

        ///


        ///
        ///

        private static string dbConnectionString = ConfigurationManager.AppSettings["ConnectionString"];

 

        private DbConnection connection;
        public DbHelper()
        {
            this.connection = CreateConnection(DbHelper.dbConnectionString);
        }
        public DbHelper(string connectionString)
        {
            this.connection = CreateConnection(connectionString);
        }
        public static DbConnection CreateConnection()
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbConnection dbconn = dbfactory.CreateConnection();
            dbconn.ConnectionString = DbHelper.dbConnectionString;
            return dbconn;
        }
        public static DbConnection CreateConnection(string connectionString)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbConnection dbconn = dbfactory.CreateConnection();
            dbconn.ConnectionString = connectionString;
            return dbconn;
        }

        ///


        /// 執行存儲過程
        ///

        ///存儲過程名
        ///
        public DbCommand GetStoredProcCommand(string storedProcedure)
        {
            DbCommand dbCommand = connection.CreateCommand();
            dbCommand.CommandText = storedProcedure;
            dbCommand.CommandType = CommandType.StoredProcedure;
            return dbCommand;
        }

 

        ///


        /// 執行SQL語句
        ///

        ///SQL語句
        ///
        public DbCommand GetSqlStringCommand(string sqlQuery)
        {
            DbCommand dbCommand = connection.CreateCommand();
            dbCommand.CommandText = sqlQuery;
            dbCommand.CommandType = CommandType.Text;
            return dbCommand;
        }

 

        #region 增加參數

        public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
        {
            foreach (DbParameter dbParameter in dbParameterCollection)
            {
                cmd.Parameters.Add(dbParameter);
            }
        }

        ///


        /// 增加輸出參數
        ///

        ///
        ///
        ///
        ///
        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Size = size;
            dbParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(dbParameter);
        }

 

        ///


        /// 增加輸入參數
        ///

        ///
        ///
        ///
        ///
        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Value = value;
            dbParameter.Direction = ParameterDirection.Input;
            cmd.Parameters.Add(dbParameter);
        }

 

        ///


        /// 增加返回參數
        ///

        ///
        ///
        ///
        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbParameter);
        }

 

        public DbParameter GetParameter(DbCommand cmd, string parameterName)
        {
            return cmd.Parameters[parameterName];
        }

        #endregion

        #region 執行

        ///


        /// 執行查詢返回DataSet
        ///

        ///
        ///
        public DataSet ExecuteDataSet(DbCommand cmd)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

 

        ///


        /// 執行查詢返回DataTable
        ///

        ///
        ///
        public DataTable ExecuteDataTable(DbCommand cmd)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);
            return dataTable;
        }

 

        ///


        /// 執行查詢返回DataReader
        ///

        ///
        ///
        public DbDataReader ExecuteReader(DbCommand cmd)
        {
            cmd.Connection.Open();
            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }

 

        ///


        /// 執行SQL語句,返回影響行數
        ///

        ///
        ///
        public int ExecuteNonQuery(DbCommand cmd)
        {
            cmd.Connection.Open();
            int ret = cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            return ret;
        }

 

        ///


        /// 返回首行首列對象
        ///

        ///
        ///
        public object ExecuteScalar(DbCommand cmd)
        {
            cmd.Connection.Open();
            object ret = cmd.ExecuteScalar();
            cmd.Connection.Close();
            return ret;
        }
        #endregion

 

        #region 執行事務

        ///


        /// 執行事務返回DataSet
        ///

        ///
        ///
        ///
        public DataSet ExecuteDataSet(DbCommand cmd, Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

 

        ///


        /// 執行事務返回DataTable
        ///

        ///
        ///
        ///
        public DataTable ExecuteDataTable(DbCommand cmd, Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);
            return dataTable;
        }

 

        ///


        /// 執行事務返回DataReader
        ///

        ///
        ///
        ///
        public DbDataReader ExecuteReader(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbDataReader reader = cmd.ExecuteReader();
            return reader;
        }

 

        ///


        /// 執行事務SQL語句返回影響行數
        ///

        ///
        ///
        ///
        public int ExecuteNonQuery(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            int ret = cmd.ExecuteNonQuery();
            return ret;
        }

 

        ///


        /// 執行事務SQL語句返回首行首列
        ///

        ///
        ///
        ///
        public object ExecuteScalar(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            object ret = cmd.ExecuteScalar();
            return ret;
        }
        #endregion
    }

 

    public class Trans : IDisposable
    {
        private DbConnection conn;
        private DbTransaction dbTrans;
        public DbConnection DbConnection
        {
            get { return this.conn; }
        }
        public DbTransaction DbTrans
        {
            get { return this.dbTrans; }
        }

        public Trans()
        {
            conn = DbHelper.CreateConnection();
            conn.Open();
            dbTrans = conn.BeginTransaction();
        }
        public Trans(string connectionString)
        {
            conn = DbHelper.CreateConnection(connectionString);
            conn.Open();
            dbTrans = conn.BeginTransaction();
        }
        public void Commit()
        {
            dbTrans.Commit();
            this.Colse();
        }

        public void RollBack()
        {
            dbTrans.Rollback();
            this.Colse();
        }

        public void Dispose()
        {
            this.Colse();
        }

        public void Colse()
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }
}
[csharp] 
using System; 
using System.Collections.Generic; 
using System.Text; 
 
namespace MSCL 

    #region 使用示例  
    /*
        List ftvlist = new List();
        ftvlist.Add(new FieldTypeValue("ErrorDetail", "這是個錯誤"));
        ftvlist.Add(new FieldTypeValue("ErrorFlag", "1"));
        ftvlist.Add(new FieldTypeValue("ErrorRemark","這是個錯誤,我還沒有處理"));
        ftvlist.Add(new FieldTypeValue("ErrorTime", DateTime.Now.ToString()));
        ftvlist.Add(new FieldTypeValue("OprationTime", DateTime.Now.ToString()));
        //新增
        string sql = MSCL.BuilderSql.createInsertSql("AFM_SysLog", ftvlist);
        MSCL.SqlHelper.ExecSql(sql);
        //修改
        string sql = MSCL.BuilderSql.createUpdateSql("AFM_SysLog", ftvlist, "ErrorID", "166");
        MSCL.SqlHelper.ExecSql(sql);
        //刪除
        string sql = MSCL.BuilderSql.createDeleteSql("AFM_SysLog", "ErrorID", "166");
        MSCL.SqlHelper.ExecSql(sql);
    */
    #endregion 
 
    #region 數據表字段類  
    ///

  
    /// 數據表字段類  
    ///
  
    public class FieldTypeValue 
    { 
        ///   
        /// 字段容器  
        ///
  
        ///字段名  
        ///字段值  
        ///是否數字字段  
        public FieldTypeValue(string fieldName, string fieldValue, bool isNum) 
        { 
            this.fieldName = fieldName; 
            this.fieldValue = fieldValue; 
            this.isNum = isNum; 
        } 
 
        ///   
        /// 字段容器  
        ///
  
        ///字段名  
        ///字段值  
        public FieldTypeValue(string fieldName, string fieldValue) 
        { 
            this.fieldName = fieldName; 
            this.fieldValue = fieldValue; 
        } 
 
        private string fieldName; 
        ///   
        /// 字段名  
        ///
  
        public string FieldName 
        { 
            get { return fieldName; } 
            set { fieldName = value; } 
        } 
 
        private bool isNum = false; 
        ///   
        /// 是否數字  
        ///
  
        public bool IsNum 
        { 
            get { return isNum; } 
            set { isNum = value; } 
        } 
 
        private string fieldValue; 
        ///   
        /// 字段值  
        ///
  
        public string FieldValue 
        { 
            get { return fieldValue; } 
            set { fieldValue = value; } 
        } 
    } 
    #endregion 
 
    #region SQL語句的構造類  
    ///   
    /// SQL語句的構造類  
    ///
  
    public class BuilderSql 
    { 
 
        ///   
        /// 構造新增Insert語句  
        ///
  
        ///表名  
        ///字段list  
        ///   
        public static string createInsertSql(string tableName, List ftvlist) 
        { 
            StringBuilder sb = new StringBuilder(); 
            sb.Append(" insert into "); 
            sb.Append(tableName); 
            sb.Append("("); 
            for (int i = 0; i < ftvlist.Count; i++) 
            { 
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i]; 
                if (i != ftvlist.Count - 1) 
                { 
                    sb.Append(ftv.FieldName + ","); 
                } 
                else 
                { 
                    sb.Append(ftv.FieldName); 
                } 
            } 
            sb.Append(") values("); 
            for (int i = 0; i < ftvlist.Count; i++) 
            { 
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i]; 
                if (ftv.IsNum) 
                { 
                    if (i != ftvlist.Count - 1) 
                    { 
                        sb.Append(ftv.FieldValue + ","); 
                    } 
                    else 
                    { 
                        sb.Append(ftv.FieldValue); 
                    } 
                } 
                else 
                { 
                    if (i != ftvlist.Count - 1) 
                    { 
                        sb.Append("'" + ftv.FieldValue + "',"); 
                    } 
                    else 
                    { 
                        sb.Append("'" + ftv.FieldValue + "'"); 
                    } 
                } 
            } 
            sb.Append(")"); 
            return sb.ToString(); 
        } 
 
 
        ///   
        /// 構造更新Update語句  
        ///
  
        ///表名  
        ///字段list  
        ///主鍵名  
        ///主鍵值  
        ///   
        public static string createUpdateSql(string tableName, List ftvlist, string pkName, string pkValue) 
        { 
            StringBuilder sb = new StringBuilder(); 
            sb.Append(" update "); 
            sb.Append(tableName); 
            sb.Append(" set"); 
            for (int i = 0; i < ftvlist.Count; i++) 
            { 
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i]; 
                if (i != ftvlist.Count - 1) 
                { 
                    if (ftv.IsNum) 
                    { 
                        sb.Append(" " + ftv.FieldName + "=" + ftv.FieldValue + ","); 
                    } 
                    else 
                    { 
                        sb.Append(" " + ftv.FieldName + "='" + ftv.FieldValue + "',"); 
                    } 
                } 
                else 
                { 
                    if (ftv.IsNum) 
                    { 
                        sb.Append(" " + ftv.FieldName + "=" + ftv.FieldValue + ""); 
                    } 
                    else 
                    { 
                        sb.Append(" " + ftv.FieldName + "='" + ftv.FieldValue + "'"); 
                    } 
                } 
            } 
            sb.Append(" where " + pkName + "=" + pkValue); 
            return sb.ToString(); 
        } 
 
        ///   
        /// 構造刪除Delete語句  
        ///
  
        ///表名  
        ///主鍵名  
        ///主鍵值  
        ///   
        public static string createDeleteSql(string tableName, string pkName, string pkValue) 
        { 
            StringBuilder sb = new StringBuilder(); 
            sb.Append(" delete from "); 
            sb.Append(tableName); 
            sb.Append(" where " + pkName + " = '" + pkValue + "'"); 
            return sb.ToString(); 
        } 
    } 
    #endregion  

 

using System;
using System.Collections.Generic;
using System.Text;

namespace MSCL
{
    #region 使用示例
    /*
        List ftvlist = new List();
        ftvlist.Add(new FieldTypeValue("ErrorDetail", "這是個錯誤"));
        ftvlist.Add(new FieldTypeValue("ErrorFlag", "1"));
        ftvlist.Add(new FieldTypeValue("ErrorRemark","這是個錯誤,我還沒有處理"));
        ftvlist.Add(new FieldTypeValue("ErrorTime", DateTime.Now.ToString()));
        ftvlist.Add(new FieldTypeValue("OprationTime", DateTime.Now.ToString()));
        //新增
        string sql = MSCL.BuilderSql.createInsertSql("AFM_SysLog", ftvlist);
        MSCL.SqlHelper.ExecSql(sql);
        //修改
        string sql = MSCL.BuilderSql.createUpdateSql("AFM_SysLog", ftvlist, "ErrorID", "166");
        MSCL.SqlHelper.ExecSql(sql);
        //刪除
        string sql = MSCL.BuilderSql.createDeleteSql("AFM_SysLog", "ErrorID", "166");
        MSCL.SqlHelper.ExecSql(sql);
    */
    #endregion

    #region 數據表字段類
    ///


    /// 數據表字段類
    ///

    public class FieldTypeValue
    {
        ///
        /// 字段容器
        ///

        ///字段名
        ///字段值
        ///是否數字字段
        public FieldTypeValue(string fieldName, string fieldValue, bool isNum)
        {
            this.fieldName = fieldName;
            this.fieldValue = fieldValue;
            this.isNum = isNum;
        }

 

        ///


        /// 字段容器
        ///

        ///字段名
        ///字段值
        public FieldTypeValue(string fieldName, string fieldValue)
        {
            this.fieldName = fieldName;
            this.fieldValue = fieldValue;
        }

 

        private string fieldName;
        ///


        /// 字段名
        ///

        public string FieldName
        {
            get { return fieldName; }
            set { fieldName = value; }
        }

 

        private bool isNum = false;
        ///


        /// 是否數字
        ///

        public bool IsNum
        {
            get { return isNum; }
            set { isNum = value; }
        }

 

        private string fieldValue;
        ///


        /// 字段值
        ///

        public string FieldValue
        {
            get { return fieldValue; }
            set { fieldValue = value; }
        }
    }
    #endregion

 

    #region SQL語句的構造類
    ///


    /// SQL語句的構造類
    ///

    public class BuilderSql
    {

 

        ///


        /// 構造新增Insert語句
        ///

        ///表名
        ///字段list
        ///
        public static string createInsertSql(string tableName, List ftvlist)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" insert into ");
            sb.Append(tableName);
            sb.Append("(");
            for (int i = 0; i < ftvlist.Count; i++)
            {
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i];
                if (i != ftvlist.Count - 1)
                {
                    sb.Append(ftv.FieldName + ",");
                }
                else
                {
                    sb.Append(ftv.FieldName);
                }
            }
            sb.Append(") values(");
            for (int i = 0; i < ftvlist.Count; i++)
            {
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i];
                if (ftv.IsNum)
                {
                    if (i != ftvlist.Count - 1)
                    {
                        sb.Append(ftv.FieldValue + ",");
                    }
                    else
                    {
                        sb.Append(ftv.FieldValue);
                    }
                }
                else
                {
                    if (i != ftvlist.Count - 1)
                    {
                        sb.Append("'" + ftv.FieldValue + "',");
                    }
                    else
                    {
                        sb.Append("'" + ftv.FieldValue + "'");
                    }
                }
            }
            sb.Append(")");
            return sb.ToString();
        }

 


        ///


        /// 構造更新Update語句
        ///

        ///表名
        ///字段list
        ///主鍵名
        ///主鍵值
        ///
        public static string createUpdateSql(string tableName, List ftvlist, string pkName, string pkValue)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" update ");
            sb.Append(tableName);
            sb.Append(" set");
            for (int i = 0; i < ftvlist.Count; i++)
            {
                FieldTypeValue ftv = (FieldTypeValue)ftvlist[i];
                if (i != ftvlist.Count - 1)
                {
                    if (ftv.IsNum)
                    {
                        sb.Append(" " + ftv.FieldName + "=" + ftv.FieldValue + ",");
                    }
                    else
                    {
                        sb.Append(" " + ftv.FieldName + "='" + ftv.FieldValue + "',");
                    }
                }
                else
                {
                    if (ftv.IsNum)
                    {
                        sb.Append(" " + ftv.FieldName + "=" + ftv.FieldValue + "");
                    }
                    else
                    {
                        sb.Append(" " + ftv.FieldName + "='" + ftv.FieldValue + "'");
                    }
                }
            }
            sb.Append(" where " + pkName + "=" + pkValue);
            return sb.ToString();
        }

 

        ///


        /// 構造刪除Delete語句
        ///

        ///表名
        ///主鍵名
        ///主鍵值
        ///
        public static string createDeleteSql(string tableName, string pkName, string pkValue)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" delete from ");
            sb.Append(tableName);
            sb.Append(" where " + pkName + " = '" + pkValue + "'");
            return sb.ToString();
        }
    }
    #endregion
}

 

[csharp] 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Text; 
using System.Data.SqlClient; 
using MSCL; 
 
public partial class SQLDemo : System.Web.UI.Page 

    DbHelper db = new DbHelper(); 
    protected void Page_Load(object sender, EventArgs e) 
    { 
        
    } 
 
    //新增數據  
    protected void Button1_Click(object sender, EventArgs e) 
    { 
        List ftvlist = new List(); 
        ftvlist.Add(new FieldTypeValue("[D_Name]", "測試用戶" + DateTime.Now.ToString("yyyyMMddhhmmss"))); 
        ftvlist.Add(new FieldTypeValue("[D_Password]", "測試密碼" + DateTime.Now.ToString("yyyyMMddhhmmss"))); 
        ftvlist.Add(new FieldTypeValue("[D_Else]", "測試備注" + DateTime.Now.ToString("yyyyMMddhhmmss"))); 
        string sql = BuilderSql.createInsertSql("TestTable", ftvlist); 
        int opFlag = db.ExecuteNonQuery(db.GetSqlStringCommand(sql)); 
        if (opFlag > 0) { JsHelper.Alert("新增成功!", Page); } else { JsHelper.Alert("新增失敗!", Page); }; 
    } 
 
    //修改數據  
    protected void Button2_Click(object sender, EventArgs e) 
    { 
        List ftvlist = new List(); 
        ftvlist.Add(new FieldTypeValue("[D_Name]", "這是個錯誤dsadsadasd")); 
        ftvlist.Add(new FieldTypeValue("[D_Password]", "aaa這是個錯誤,我還沒有處理")); 
        ftvlist.Add(new FieldTypeValue("[D_Else]", "aaa這是個錯誤,我還沒有處理")); 
        string sql = BuilderSql.createUpdateSql("TestTable", ftvlist, "D_ID", "1"); 
        int opFlag = db.ExecuteNonQuery(db.GetSqlStringCommand(sql)); 
        if (opFlag > 0) { JsHelper.Alert("修改成功!", Page); } else { JsHelper.Alert("修改失敗!", Page); }; 
    } 
 
    //刪除數據  
    protected void Button3_Click(object sender, EventArgs e) 
    { 
        string sql = BuilderSql.createDeleteSql("[TestTable]", "[D_Id]", "1"); 
        int opFlag = db.ExecuteNonQuery(db.GetSqlStringCommand(sql)); 
        if (opFlag > 0) { JsHelper.Alert("刪除成功!", Page); } else { JsHelper.Alert("刪除失敗!", Page); }; 
    } 
 
    //事務提交  
    protected void Button4_Click(object sender, EventArgs e) 
    { 
        using (Trans t = new Trans()) 
        { 
            try 
            { 
                db.ExecuteNonQuery(db.GetSqlStringCommand("insert into TestTable(D_Name,D_Password,D_Else) values('aaaaa1','bbbbbb1','cccccc1')"), t); 
                db.ExecuteNonQuery(db.GetSqlStringCommand("insert into TestTable(D_Name,D_Password,D_Else) values('aaaaa2','bbbbbb2','cccccc2')"), t); 
                db.ExecuteNonQuery(db.GetSqlStringCommand("insert into TestTable(D_Name,D_Password,D_Else) values('aaaaa3','bbbbbb3','cccccc3')"), t); 
                db.ExecuteNonQuery(db.GetSqlStringCommand("insert into TestTable(D_Name,D_Password,D_Else) values('aaaaa4','bbbbbb4','cccccc4')"), t); 
                db.ExecuteNonQuery(db.GetSqlStringCommand("insert into TestTable(D_Name,D_Password,D_Else) values('aaaaa5','bbbbbb5','cccccc5')"), t); 
                t.Commit(); 
                JsHelper.Alert("事務提交成功!", Page); 
            } 
            catch 
            { 
                t.RollBack(); 
                JsHelper.Alert("事務提交失敗!", Page); 
            } 
        } 
    } 
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved