using System; using System.Data; using System.Data.Common; using System.Configuration; namespace MSCL { /// <summary> /// DbHelper通用数据库类 /// </summary> public class DbHelper { /// <summary> /// <add key="DbHelperProvider" value="System.Data.SqlClient"/> /// </summary> private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"]; /// <summary> /// <add key="DbHelperConnectionString" value="Data Source=(local);Initial Catalog=DbHelperTest;Persist Security Info=True;User ID=sa;Password=sa"/> /// </summary> 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; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcedure">存储过程名</param> /// <returns></returns> public DbCommand GetStoredProcCommand(string storedProcedure) { DbCommand dbCommand = connection.CreateCommand(); dbCommand.CommandText = storedProcedure; dbCommand.CommandType = CommandType.StoredProcedure; return dbCommand; } /// <summary> /// 执行SQL语句 /// </summary> /// <param name="sqlQuery">SQL语句</param> /// <returns></returns> 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); } } /// <summary> /// 增加输出参数 /// </summary> /// <param name="cmd"></param> /// <param name="parameterName"></param> /// <param name="dbType"></param> /// <param name="size"></param> 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); } /// <summary> /// 增加输入参数 /// </summary> /// <param name="cmd"></param> /// <param name="parameterName"></param> /// <param name="dbType"></param> /// <param name="value"></param> 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); } /// <summary> /// 增加返回参数 /// </summary> /// <param name="cmd"></param> /// <param name="parameterName"></param> /// <param name="dbType"></param> 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 执行 /// <summary> /// 执行查询返回DataSet /// </summary> /// <param name="cmd"></param> /// <returns></returns> 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; } /// <summary> /// 执行查询返回DataTable /// </summary> /// <param name="cmd"></param> /// <returns></returns> 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; } /// <summary> /// 执行查询返回DataReader /// </summary> /// <param name="cmd"></param> /// <returns></returns> public DbDataReader ExecuteReader(DbCommand cmd) { cmd.Connection.Open(); DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return reader; } /// <summary> /// 执行SQL语句,返回影响行数 /// </summary> /// <param name="cmd"></param> /// <returns></returns> public int ExecuteNonQuery(DbCommand cmd) { cmd.Connection.Open(); int ret = cmd.ExecuteNonQuery(); cmd.Connection.Close(); return ret; } /// <summary> /// 返回首行首列对象 /// </summary> /// <param name="cmd"></param> /// <returns></returns> public object ExecuteScalar(DbCommand cmd) { cmd.Connection.Open(); object ret = cmd.ExecuteScalar(); cmd.Connection.Close(); return ret; } #endregion #region 执行事务 /// <summary> /// 执行事务返回DataSet /// </summary> /// <param name="cmd"></param> /// <param name="t"></param> /// <returns></returns> 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; } /// <summary> /// 执行事务返回DataTable /// </summary> /// <param name="cmd"></param> /// <param name="t"></param> /// <returns></returns> 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; } /// <summary> /// 执行事务返回DataReader /// </summary> /// <param name="cmd"></param> /// <param name="t"></param> /// <returns></returns> public DbDataReader ExecuteReader(DbCommand cmd, Trans t) { cmd.Connection.Close(); cmd.Connection = t.DbConnection; cmd.Transaction = t.DbTrans; DbDataReader reader = cmd.ExecuteReader(); return reader; } /// <summary> /// 执行事务SQL语句返回影响行数 /// </summary> /// <param name="cmd"></param> /// <param name="t"></param> /// <returns></returns> public int ExecuteNonQuery(DbCommand cmd, Trans t) { cmd.Connection.Close(); cmd.Connection = t.DbConnection; cmd.Transaction = t.DbTrans; int ret = cmd.ExecuteNonQuery(); return ret; } /// <summary> /// 执行事务SQL语句返回首行首列 /// </summary> /// <param name="cmd"></param> /// <param name="t"></param> /// <returns></returns> 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.Collections.Generic; using System.Text; namespace MSCL { #region 使用示例 /* List<FieldTypeValue> ftvlist = new List<FieldTypeValue>(); 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 数据表字段类 /// <summary> /// 数据表字段类 /// </summary> public class FieldTypeValue { /// <summary> /// 字段容器 /// </summary> /// <param name="fieldName">字段名</param> /// <param name="fieldValue">字段值</param> /// <param name="isNum">是否数字字段</param> public FieldTypeValue(string fieldName, string fieldValue, bool isNum) { this.fieldName = fieldName; this.fieldValue = fieldValue; this.isNum = isNum; } /// <summary> /// 字段容器 /// </summary> /// <param name="fieldName">字段名</param> /// <param name="fieldValue">字段值</param> public FieldTypeValue(string fieldName, string fieldValue) { this.fieldName = fieldName; this.fieldValue = fieldValue; } private string fieldName; /// <summary> /// 字段名 /// </summary> public string FieldName { get { return fieldName; } set { fieldName = value; } } private bool isNum = false; /// <summary> /// 是否数字 /// </summary> public bool IsNum { get { return isNum; } set { isNum = value; } } private string fieldValue; /// <summary> /// 字段值 /// </summary> public string FieldValue { get { return fieldValue; } set { fieldValue = value; } } } #endregion #region SQL语句的构造类 /// <summary> /// SQL语句的构造类 /// </summary> public class BuilderSql { /// <summary> /// 构造新增Insert语句 /// </summary> /// <param name="tableName">表名</param> /// <param name="ftvlist">字段list</param> /// <returns></returns> public static string createInsertSql(string tableName, List<FieldTypeValue> 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(); } /// <summary> /// 构造更新Update语句 /// </summary> /// <param name="tableName">表名</param> /// <param name="ftvlist">字段list</param> /// <param name="pkName">主键名</param> /// <param name="pkValue">主键值</param> /// <returns></returns> public static string createUpdateSql(string tableName, List<FieldTypeValue> 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(); } /// <summary> /// 构造删除Delete语句 /// </summary> /// <param name="tableName">表名</param> /// <param name="pkName">主键名</param> /// <param name="pkValue">主键值</param> /// <returns></returns> 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.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<FieldTypeValue> ftvlist = new List<FieldTypeValue>(); 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<FieldTypeValue> ftvlist = new List<FieldTypeValue>(); 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); } } } }