SqlHelper.cs
上传用户:simon2hong
上传日期:2021-11-18
资源大小:16746k
文件大小:10k
源码类别:

OA系统

开发平台:

C#

  1. using System;
  2. using System.Data;
  3. using System.Data.Common;
  4. using System.Text;
  5. using System.Data.SqlClient;
  6. namespace DBUtility
  7. {
  8.     /// <summary>
  9.     /// 数据库操作基类(for Sql2000/2005)
  10.     /// </summary>
  11.     public class SqlHelper : IDBHelper
  12.     {
  13.         /// <summary>
  14.         /// 获取分页SQL
  15.         /// </summary>
  16.         /// <param name="tblName">表名</param>
  17.         /// <param name="pageSize">每页显示条数</param>
  18.         /// <param name="pageIndex">第几页</param>
  19.         /// <param name="fldSort">排序字段(最后一个不需要填写正序还是倒序,例如:id asc, name)</param>
  20.         /// <param name="fldDir">最后一个排序字段的正序或倒序(true为倒序,false为正序)</param>
  21.         /// <param name="condition">条件</param>
  22.         /// <returns>返回用于分页的SQL语句</returns>
  23.         public string GetPagerSQL(string tblName, int pageSize, int pageIndex, string fldSort, bool fldDir, string condition)
  24.         {
  25.             string strDir = fldDir ? " ASC" : " DESC";
  26.             if (pageIndex == 1)
  27.             {
  28.                 return "select top " + pageSize.ToString() + " * from " + tblName.ToString()
  29.                     + ((string.IsNullOrEmpty(condition)) ? string.Empty : (" where " + condition))
  30.                     + " order by " + fldSort.ToString() + strDir;
  31.             }
  32.             else
  33.             {
  34.                 StringBuilder strSql = new StringBuilder();
  35.                 strSql.AppendFormat("select top {0} * from {1} ", pageSize, tblName);
  36.                 strSql.AppendFormat(" where {1} not in (select top {0} {1} from {2} ", pageSize * (pageIndex - 1),
  37.                     (fldSort.Substring(fldSort.LastIndexOf(',') + 1, fldSort.Length - fldSort.LastIndexOf(',') - 1)), tblName);
  38.                 if (!string.IsNullOrEmpty(condition))
  39.                 {
  40.                     strSql.AppendFormat(" where {0} order by {1}{2}) and {0}", condition, fldSort, strDir);
  41.                 }
  42.                 else
  43.                 {
  44.                     strSql.AppendFormat(" order by {0}{1}) ", fldSort, strDir);
  45.                 }
  46.                 strSql.AppendFormat(" order by {0}{1}", fldSort, strDir);
  47.                 return strSql.ToString();
  48.             }
  49.         }
  50.         /// <summary>
  51.         /// 分页获取数据
  52.         /// </summary>
  53.         /// <param name="connectionString">连接字符串</param>
  54.         /// <param name="tblName">表名</param>
  55.         /// <param name="fldName">字段名</param>
  56.         /// <param name="pageSize">页大小</param>
  57.         /// <param name="pageIndex">第几页</param>
  58.         /// <param name="fldSort">排序字段</param>
  59.         /// <param name="fldDir">升序{False}/降序(True)</param>
  60.         /// <param name="condition">条件(不需要where)</param>
  61.         public DbDataReader GetPageList(string connectionString, string tblName, int pageSize,
  62.             int pageIndex, string fldSort, bool fldDir, string condition)
  63.         {
  64.             string sql = GetPagerSQL(tblName, pageSize, pageIndex, fldSort, fldDir, condition);
  65.             return ExecuteReader(connectionString, CommandType.Text, sql, null);
  66.         }
  67.         /// <summary>
  68.         /// 得到数据条数
  69.         /// </summary>
  70.         public int GetCount(string connectionString, string tblName, string condition)
  71.         {
  72.             StringBuilder sql = new StringBuilder("select count(*) from " + tblName);
  73.             if (!string.IsNullOrEmpty(condition))
  74.                 sql.Append(" where " + condition);
  75.             object count = ExecuteScalar(connectionString, CommandType.Text, sql.ToString(), null);
  76.             return int.Parse(count.ToString());
  77.         }
  78.         /// <summary>
  79.         /// 执行查询,返回DataSet
  80.         /// </summary>
  81.         public DataSet ExecuteQuery(string connectionString, CommandType cmdType, string cmdText,
  82.             params DbParameter[] cmdParms)
  83.         {
  84.             using (SqlConnection conn = new SqlConnection(connectionString))
  85.             {
  86.                 using (SqlCommand cmd = new SqlCommand())
  87.                 {
  88.                     PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
  89.                     using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  90.                     {
  91.                         DataSet ds = new DataSet();
  92.                         da.Fill(ds, "ds");
  93.                         cmd.Parameters.Clear();
  94.                         return ds;
  95.                     }
  96.                 }
  97.             }
  98.         }
  99.         /// <summary>
  100.         /// 在事务中执行查询,返回DataSet
  101.         /// </summary>
  102.         public DataSet ExecuteQuery(DbTransaction trans, CommandType cmdType, string cmdText,
  103.             params DbParameter[] cmdParms)
  104.         {
  105.             SqlCommand cmd = new SqlCommand();
  106.             PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
  107.             SqlDataAdapter da = new SqlDataAdapter(cmd);
  108.             DataSet ds = new DataSet();
  109.             da.Fill(ds, "ds");
  110.             cmd.Parameters.Clear();
  111.             return ds;
  112.         }
  113.         /// <summary>
  114.         /// 执行 Transact-SQL 语句并返回受影响的行数。
  115.         /// </summary>
  116.         public int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText,
  117.             params DbParameter[] cmdParms)
  118.         {
  119.             SqlCommand cmd = new SqlCommand();
  120.             using (SqlConnection conn = new SqlConnection(connectionString))
  121.             {
  122.                 PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
  123.                 int val = cmd.ExecuteNonQuery();
  124.                 cmd.Parameters.Clear();
  125.                 return val;
  126.             }
  127.         }
  128.         /// <summary>
  129.         /// 在事务中执行 Transact-SQL 语句并返回受影响的行数。
  130.         /// </summary>
  131.         public int ExecuteNonQuery(DbTransaction trans, CommandType cmdType, string cmdText,
  132.             params DbParameter[] cmdParms)
  133.         {
  134.             
  135.             SqlCommand cmd = new SqlCommand();
  136.             PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
  137.             int val = cmd.ExecuteNonQuery();
  138.             cmd.Parameters.Clear();
  139.             return val;
  140.         }
  141.         /// <summary>
  142.         /// 执行查询,返回DataReader
  143.         /// </summary>
  144.         public DbDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText,
  145.             params DbParameter[] cmdParms)
  146.         {
  147.             SqlCommand cmd = new SqlCommand();
  148.             SqlConnection conn = new SqlConnection(connectionString);
  149.             try
  150.             {
  151.                 PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
  152.                 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  153.                 cmd.Parameters.Clear();
  154.                 return rdr;
  155.             }
  156.             catch (Exception e)
  157.             {
  158.                 conn.Close();
  159.                 throw e;
  160.             }
  161.         }
  162.         /// <summary>
  163.         /// 在事务中执行查询,返回DataReader
  164.         /// </summary>
  165.         public DbDataReader ExecuteReader(DbTransaction trans, CommandType cmdType, string cmdText,
  166.             params DbParameter[] cmdParms)
  167.         {
  168.             SqlCommand cmd = new SqlCommand();
  169.             PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
  170.             SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  171.             cmd.Parameters.Clear();
  172.             return rdr;
  173.         }
  174.         /// <summary>
  175.         /// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
  176.         /// </summary>
  177.         public object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText,
  178.             params DbParameter[] cmdParms)
  179.         {
  180.             SqlCommand cmd = new SqlCommand();
  181.             using (SqlConnection connection = new SqlConnection(connectionString))
  182.             {
  183.                 PrepareCommand(cmd, connection, null, cmdType, cmdText, cmdParms);
  184.                 object val = cmd.ExecuteScalar();
  185.                 cmd.Parameters.Clear();
  186.                 return val;
  187.             }
  188.         }
  189.         /// <summary>
  190.         /// 在事务中执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
  191.         /// </summary>
  192.         public object ExecuteScalar(DbTransaction trans, CommandType cmdType, string cmdText,
  193.             params DbParameter[] cmdParms)
  194.         {
  195.             SqlCommand cmd = new SqlCommand();
  196.             PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
  197.             object val = cmd.ExecuteScalar();
  198.             cmd.Parameters.Clear();
  199.             return val;
  200.         }
  201.         /// <summary>
  202.         /// 生成要执行的命令
  203.         /// </summary>
  204.         private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, CommandType cmdType,
  205.             string cmdText, DbParameter[] cmdParms)
  206.         {
  207.             // 如果存在参数,则表示用户是用参数形式的SQL语句,可以替换
  208.             if (cmdParms != null && cmdParms.Length > 0)
  209.                 cmdText = cmdText.Replace("?", "@").Replace(":", "@");
  210.             if (conn.State != ConnectionState.Open)
  211.                 conn.Open();
  212.             cmd.Connection = conn;
  213.             cmd.CommandText = cmdText;
  214.             if (trans != null)
  215.                 cmd.Transaction = trans;
  216.             cmd.CommandType = cmdType;
  217.             if (cmdParms != null)
  218.             {
  219.                 foreach (SqlParameter parm in cmdParms)
  220.                 {
  221.                     parm.ParameterName = parm.ParameterName.Replace("?", "@").Replace(":", "@");
  222.                     cmd.Parameters.Add(parm);
  223.                 }
  224.             }
  225.         }
  226.     }
  227. }