SqlDbHelper
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace Agco.Data { public class SqlHelper { public readonly string connString; public SqlHelper() { connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); } public SqlHelper(string conn) { connString = conn; } #region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public int ExecuteNonQuery(string strSql) { int rst = -9999; try { SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(strSql, sqlConn); SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { rst = cm.ExecuteNonQuery(); tran.Commit(); return rst; } catch (Exception e) { string msg = e.Message; tran.Rollback(); return rst; } finally { cm = null; sqlConn.Close(); }//try } catch { return rst; } }//ExcuteNoQuery #endregion #region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public bool ExecuteNonQuery(List<string> sqllist) { bool rst = true; try { SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(); cm.Connection = sqlConn; SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { for (int i = 0; i < sqllist.Count; i++) { cm.CommandText = sqllist[i]; cm.ExecuteNonQuery(); } tran.Commit(); } catch (Exception e) { rst = false; string msg = e.Message; tran.Rollback(); rst=false; } finally { cm = null; sqlConn.Close(); }//try } catch { rst=false; } return rst; }//ExcuteNoQuery #endregion #region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <param name="type">sql命令类型</param> ///<param name="paras">sql命令的参数集合</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public int ExecuteNonQuery(string strSql, CommandType type, SqlParameter[] paras) { int rst = -9999; try { SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(strSql, sqlConn); SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras); rst = cm.ExecuteNonQuery(); tran.Commit(); cm.Parameters.Clear(); return rst; } catch (Exception e) { string msg = e.Message; tran.Rollback(); return rst; } finally { cm = null; sqlConn.Close(); }//try } catch { return rst; } }//ExcuteNoQuery #endregion #region 返回ExecuteScalar值 /// <summary> /// 执行一个SQL命令,并返回结果集中的首行首列。 /// 该方法通常用来执行包含Count、Sum等聚合函数的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返并返回结果集中的首行首列。</returns> public object ExecuteScalar(string strSql) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); try { sqlConn.Open(); return cm.ExecuteScalar(); } catch (Exception e) { return null; } finally { cm = null; sqlConn.Close(); } }//ExcuteScalar #endregion #region 返回ExecuteScalar值 /// <summary> /// 执行一个SQL命令,并返回结果集中的首行首列。 /// 该方法通常用来执行包含Count、Sum等聚合函数的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返并返回结果集中的首行首列。</returns> public object ExecuteScalar(string strSql, CommandType type, SqlParameter[] paras) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras); try { sqlConn.Open(); return cm.ExecuteScalar(); } catch (Exception e) { return null; } finally { cm.Parameters.Clear(); cm = null; sqlConn.Close(); } }//ExcuteScalar #endregion #region 返回DataTable /// <summary> /// 获取一个DataTable对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <param name="strTableName">内存中的表的名称</param> /// <returns>返回DataTable对象</returns> public DataTable ReturnDataTable(string strSql, string strTableName) { SqlConnection con = new SqlConnection(connString); con.Open(); SqlDataAdapter da = new SqlDataAdapter(strSql, con); DataTable dt = new DataTable(strTableName); //DataColumn dc = new DataColumn("tblXuHao"); //dc.DataType = System.Type.GetType("System.Int32"); //dc.AutoIncrement = true; //dc.AutoIncrementSeed = 1; //dc.AutoIncrementStep = 1; //dt.Columns.Add(dc); //===================================================== try { da.Fill(dt); return dt; } finally { da = null; dt = null; con.Close(); // dc = null; } } #endregion #region 返回DataTable /// <summary> /// 获取一个DataTable对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <param name="strTableName">内存中的表的名称</param> /// <returns>返回DataTable对象</returns> public DataTable ReturnDataTable(string strSql, string strTableName, CommandType type, SqlParameter[] paras) { SqlConnection con = new SqlConnection(connString); con.Open(); SqlCommand cm = new SqlCommand(strSql, con); cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras); SqlDataAdapter da = new SqlDataAdapter(cm); DataSet ds = new DataSet(); DataTable dt = new DataTable(strTableName); ds.Tables.Add(dt); DataColumn dc = new DataColumn("tblXuHao"); dc.DataType = System.Type.GetType("System.Int32"); dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; dt.Columns.Add(dc); //===================================================== try { da.Fill(ds, strTableName); cm.Parameters.Clear(); return ds.Tables[strTableName]; } finally { da = null; dt = null; con.Close(); // dc = null; } } #endregion #region 返回SqlDataReader /// <summary> /// 获取SqlDataReader对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <returns>返回SqlDataReader对象</returns> public SqlDataReader ExecuteReader(string strSql, SqlParameter[] paras) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); if (paras != null) { cm.Parameters.AddRange(paras); } try { sqlConn.Open(); return cm.ExecuteReader(CommandBehavior.CloseConnection); } finally { cm = null; sqlConn.Close(); } } /// <summary> /// 获取SqlDataReader对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <returns>返回SqlDataReader对象</returns> public SqlDataReader ExecuteReader(string strSql) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); try { sqlConn.Open(); return cm.ExecuteReader(CommandBehavior.CloseConnection); } finally { cm = null; sqlConn.Close(); } } /// <summary> /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlDataReader</returns> public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> private SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } #endregion #region SqlDataReader to IList<T> 需保持表名和属性名一直 public IList<T> GetList<T>(string strSql) { SqlDataReader sqldatareader = ExecuteReader(strSql); try { IList<T> list = new List<T>(); while (sqldatareader.Read()) { T t = System.Activator.CreateInstance<T>(); Type type = t.GetType(); for (int i = 0; i < sqldatareader.FieldCount; i++) { object TempValue = null; if (sqldatareader.IsDBNull(i)) { string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName; TempValue = GetDbNullValue(typeFullName); } else { TempValue = sqldatareader.GetValue(i); } type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null); } list.Add(t); } return list; } catch (Exception ex) { throw ex; } finally { sqldatareader.Close(); sqldatareader.Dispose(); } } public IList<T> GetList<T>(string strSql, SqlParameter[] paras) { SqlDataReader sqldatareader = ExecuteReader(strSql, paras); try { IList<T> list = new List<T>(); while (sqldatareader.Read()) { T t = System.Activator.CreateInstance<T>(); Type type = t.GetType(); for (int i = 0; i < sqldatareader.FieldCount; i++) { object TempValue = null; if (sqldatareader.IsDBNull(i)) { string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName; TempValue = GetDbNullValue(typeFullName); } else { TempValue = sqldatareader.GetValue(i); } type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null); } list.Add(t); } return list; } catch (Exception ex) { throw ex; } finally { sqldatareader.Close(); sqldatareader.Dispose(); } } public object GetDbNullValue(string typeFullName) { typeFullName = typeFullName.ToLower(); if (typeFullName == "string") return string.Empty; else if (typeFullName == "int32" || typeFullName == "int16" || typeFullName == "int64") return 0; else if (typeFullName == "datetime") return Convert.ToDateTime(DateTime.MinValue); else if (typeFullName == "boolean") return false; else if (typeFullName == "int") return 0; return null; } #endregion } }
using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;
namespace Agco.Data{ public class SqlHelper { public readonly string connString; public SqlHelper() { connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); } public SqlHelper(string conn) { connString = conn; } #region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public int ExecuteNonQuery(string strSql) { int rst = -9999; try {
SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(strSql, sqlConn); SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { rst = cm.ExecuteNonQuery(); tran.Commit(); return rst; } catch (Exception e) { string msg = e.Message; tran.Rollback(); return rst; } finally { cm = null; sqlConn.Close(); }//try } catch { return rst; } }//ExcuteNoQuery #endregion #region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public bool ExecuteNonQuery(List<string> sqllist) { bool rst = true; try {
SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(); cm.Connection = sqlConn; SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { for (int i = 0; i < sqllist.Count; i++) { cm.CommandText = sqllist[i]; cm.ExecuteNonQuery(); } tran.Commit(); } catch (Exception e) { rst = false; string msg = e.Message; tran.Rollback(); rst=false; } finally { cm = null; sqlConn.Close(); }//try } catch { rst=false; } return rst; }//ExcuteNoQuery #endregion
#region 执行NonQuery /// <summary> /// 用来执行Insert、Update、Delete和其他没有返回结果集的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <param name="type">sql命令类型</param> ///<param name="paras">sql命令的参数集合</param> /// <returns>返回结果!= -9999 执行成功,返回-9999执行失败</returns> public int ExecuteNonQuery(string strSql, CommandType type, SqlParameter[] paras) { int rst = -9999; try {
SqlConnection sqlConn = new SqlConnection(connString); sqlConn.Open(); SqlCommand cm = new SqlCommand(strSql, sqlConn); SqlTransaction tran = sqlConn.BeginTransaction(); cm.Transaction = tran; try { cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras);
rst = cm.ExecuteNonQuery(); tran.Commit(); cm.Parameters.Clear(); return rst; } catch (Exception e) { string msg = e.Message; tran.Rollback(); return rst; } finally { cm = null; sqlConn.Close(); }//try } catch { return rst; } }//ExcuteNoQuery #endregion
#region 返回ExecuteScalar值 /// <summary> /// 执行一个SQL命令,并返回结果集中的首行首列。 /// 该方法通常用来执行包含Count、Sum等聚合函数的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返并返回结果集中的首行首列。</returns> public object ExecuteScalar(string strSql) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); try { sqlConn.Open(); return cm.ExecuteScalar(); } catch (Exception e) { return null; } finally { cm = null; sqlConn.Close(); } }//ExcuteScalar #endregion
#region 返回ExecuteScalar值 /// <summary> /// 执行一个SQL命令,并返回结果集中的首行首列。 /// 该方法通常用来执行包含Count、Sum等聚合函数的SQL语句 /// </summary> /// <param name="strSql">传入要执行的SQL语句</param> /// <returns>返并返回结果集中的首行首列。</returns> public object ExecuteScalar(string strSql, CommandType type, SqlParameter[] paras) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras); try { sqlConn.Open();
return cm.ExecuteScalar();
} catch (Exception e) { return null; } finally { cm.Parameters.Clear(); cm = null; sqlConn.Close(); } }//ExcuteScalar #endregion
#region 返回DataTable /// <summary> /// 获取一个DataTable对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <param name="strTableName">内存中的表的名称</param> /// <returns>返回DataTable对象</returns> public DataTable ReturnDataTable(string strSql, string strTableName) { SqlConnection con = new SqlConnection(connString); con.Open(); SqlDataAdapter da = new SqlDataAdapter(strSql, con); DataTable dt = new DataTable(strTableName);
//DataColumn dc = new DataColumn("tblXuHao"); //dc.DataType = System.Type.GetType("System.Int32"); //dc.AutoIncrement = true; //dc.AutoIncrementSeed = 1; //dc.AutoIncrementStep = 1; //dt.Columns.Add(dc); //===================================================== try { da.Fill(dt);
return dt; } finally { da = null; dt = null; con.Close(); // dc = null; } } #endregion
#region 返回DataTable /// <summary> /// 获取一个DataTable对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <param name="strTableName">内存中的表的名称</param> /// <returns>返回DataTable对象</returns> public DataTable ReturnDataTable(string strSql, string strTableName, CommandType type, SqlParameter[] paras) { SqlConnection con = new SqlConnection(connString); con.Open(); SqlCommand cm = new SqlCommand(strSql, con); cm.Parameters.Clear(); cm.CommandText = strSql; cm.CommandType = type; if (paras != null) cm.Parameters.AddRange(paras); SqlDataAdapter da = new SqlDataAdapter(cm); DataSet ds = new DataSet(); DataTable dt = new DataTable(strTableName); ds.Tables.Add(dt);
DataColumn dc = new DataColumn("tblXuHao"); dc.DataType = System.Type.GetType("System.Int32"); dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; dt.Columns.Add(dc); //===================================================== try { da.Fill(ds, strTableName); cm.Parameters.Clear(); return ds.Tables[strTableName]; } finally { da = null; dt = null; con.Close(); // dc = null; } }
#endregion
#region 返回SqlDataReader /// <summary> /// 获取SqlDataReader对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <returns>返回SqlDataReader对象</returns> public SqlDataReader ExecuteReader(string strSql, SqlParameter[] paras) { SqlConnection sqlConn = new SqlConnection(connString); SqlCommand cm = new SqlCommand(strSql, sqlConn); if (paras != null) { cm.Parameters.AddRange(paras); } try { sqlConn.Open(); return cm.ExecuteReader(CommandBehavior.CloseConnection); } finally { cm = null; sqlConn.Close(); } }
/// <summary> /// 获取SqlDataReader对象 /// </summary> /// <param name="strSql">传入的SQL语句</param> /// <returns>返回SqlDataReader对象</returns> public SqlDataReader ExecuteReader(string strSql) { SqlConnection sqlConn = new SqlConnection(connString);
SqlCommand cm = new SqlCommand(strSql, sqlConn); try { sqlConn.Open(); return cm.ExecuteReader(CommandBehavior.CloseConnection); } finally { cm = null; sqlConn.Close(); } }
/// <summary> /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlDataReader</returns> public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader;
}
/// <summary> /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand</returns> private SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } }
return command; } #endregion
#region SqlDataReader to IList<T> 需保持表名和属性名一直
public IList<T> GetList<T>(string strSql) { SqlDataReader sqldatareader = ExecuteReader(strSql); try { IList<T> list = new List<T>(); while (sqldatareader.Read()) { T t = System.Activator.CreateInstance<T>(); Type type = t.GetType(); for (int i = 0; i < sqldatareader.FieldCount; i++) { object TempValue = null; if (sqldatareader.IsDBNull(i)) { string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName; TempValue = GetDbNullValue(typeFullName); } else { TempValue = sqldatareader.GetValue(i); } type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null); } list.Add(t);
} return list; } catch (Exception ex) { throw ex; } finally { sqldatareader.Close(); sqldatareader.Dispose(); } }
public IList<T> GetList<T>(string strSql, SqlParameter[] paras) { SqlDataReader sqldatareader = ExecuteReader(strSql, paras); try { IList<T> list = new List<T>(); while (sqldatareader.Read()) { T t = System.Activator.CreateInstance<T>(); Type type = t.GetType(); for (int i = 0; i < sqldatareader.FieldCount; i++) { object TempValue = null; if (sqldatareader.IsDBNull(i)) { string typeFullName = type.GetProperty(sqldatareader.GetName(i)).PropertyType.FullName; TempValue = GetDbNullValue(typeFullName); } else { TempValue = sqldatareader.GetValue(i); } type.GetProperty(sqldatareader.GetName(i)).SetValue(t, TempValue, null); } list.Add(t);
} return list; } catch (Exception ex) { throw ex; } finally { sqldatareader.Close(); sqldatareader.Dispose(); } }
public object GetDbNullValue(string typeFullName) { typeFullName = typeFullName.ToLower(); if (typeFullName == "string") return string.Empty; else if (typeFullName == "int32" || typeFullName == "int16" || typeFullName == "int64") return 0; else if (typeFullName == "datetime") return Convert.ToDateTime(DateTime.MinValue); else if (typeFullName == "boolean") return false; else if (typeFullName == "int") return 0; return null; }
#endregion }}
posted on 2018-01-19 11:01 YellowCool 阅读(325) 评论(0) 编辑 收藏 举报