DBHelper数据库操作类(二)

不错文章:http://www.codefans.net/articles/562.shtml

http://www.cnblogs.com/gaobing/p/3878342.html

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Reflection;
using System.Collections;
namespace DataHelp
{
    #region ADO.NET 访问数据库辅助类 +SqlHelp
    //Author:兵兵 +SqlHelp
    public class SqlHelp
    {
        /// <summary>
        /// DB连接字符串
        /// </summary>
        public static readonly string DB= ConfigurationManager.ConnectionStrings["DB"].ConnectionString;

        #region ExecuteDataReader +ExecuteDataReader(string cmdText, List<SqlParameter> parameters,string connString)
        /// <summary>
        /// ExecuteDataReader(执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>SqlDataReader对象</returns>
        public static SqlDataReader ExecuteDataReader(string cmdText, List<SqlParameter> parameters, string connString)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand();
            CommandBuilder(cmdText, cmd, conn, parameters);
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return reader;

        }
        #endregion

        #region ExecuteDataReader +ExecuteDataReader(string cmdText,string connString)
        /// <summary>
        /// ExecuteDataReader(执行无参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>SqlDataReader对象</returns>
        public static SqlDataReader ExecuteDataReader(string cmdText, string connString)
        {

            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand();
            CommandBuilder(cmdText, cmd, conn);
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return reader;

        }
        #endregion

        #region ExecuteNonQuery +ExecuteNonQuery(string cmdText, List<SqlParameter> parameters, string connString)
        /// <summary>
        /// ExecuteNonQuery(执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>数据库受影响的行数</returns>
        public static int ExecuteNonQuery(string cmdText, List<SqlParameter> parameters, string connString)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn, parameters);
                int result = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return result;
            }
        }
        #endregion

        #region ExecuteNonQuery +ExecuteNonQuery(string cmdText, string connString)
        /// <summary>
        /// ExecuteNonQuery(执行无参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>数据库受影响的行数</returns>
        public static int ExecuteNonQuery(string cmdText, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn);
                int result = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return result;
            }

        }
        #endregion

        #region ExecuteScalar +ExecuteScalar(string cmdText, List<SqlParameter> parameters, string connString)
        /// <summary>
        /// ExecuteScalar(执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>object</returns>
        public static object ExecuteScalar(string cmdText, List<SqlParameter> parameters, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn, parameters);
                object o = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return o;
            }

        }
        #endregion

        #region ExecuteScalar +ExecuteScalar(string cmdText, string connString)
        /// <summary>
        /// ExecuteScalar(执行无参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>object</returns>
        public static object ExecuteScalar(string cmdText, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn);
                object o = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return o;
            }

        }
        #endregion

        #region ExecuteDataTable +ExecuteDataTable(string cmdText, List<SqlParameter> parameters, string connString)
        /// <summary>
        /// ExecuteDataTable(用适配器执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecuteDataTable(string cmdText, List<SqlParameter> parameters, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
                //命令类型为存储过程
                da.DeleteCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.AddRange(parameters.ToArray());
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }

        }
        #endregion

        #region ExecuteDataTable +ExecuteDataTable(string cmdText, string connString)
        /// <summary>
        /// ExecuteDataTable(用适配器执行无参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecuteDataTable(string cmdText, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
                //命令类型为存储过程
                da.DeleteCommand.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }
        #endregion

        #region ExecuteDataTableProc(命令+适配器) +ExecuteDataTableProc(string cmdText, List<SqlParameter> parameters, string connString)
        /// <summary>
        /// ExecuteDataTableProc(执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecuteDataTableProc(string cmdText, List<SqlParameter> parameters, string connString)
        /// <summary>
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn, parameters);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                cmd.Parameters.Clear();
                return dt;

            }

        }
        #endregion

        #region ExecuteDataTableProc(命令+适配器) +ExecuteDataTableProc(string cmdText, string connString)
        /// <summary>
        /// ExecuteDataTableProc(执行无参存储过程)
        /// </summary>
        /// <param name="parameters">参数列表</param>
        /// <param name="connString">连接字符串</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecuteDataTableProc(string cmdText, string connString)
        {

            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                CommandBuilder(cmdText, cmd, conn);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                cmd.Parameters.Clear();
                return dt;

            }

        }
        #endregion

        #region 准备命令对象 -CommandBuilder(string cmdText, SqlCommand cmd, SqlConnection conn, List<SqlParameter> parameters)
        /// <summary>
        /// 准备命令对象(执行有参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="cmd">命令对象</param>
        /// <param name="conn">连接对象</param>
        /// <param name="parameters">参数列表</param>
        private static void CommandBuilder(string cmdText, SqlCommand cmd, SqlConnection conn, List<SqlParameter> parameters)
        {

            if (conn.State == System.Data.ConnectionState.Closed)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            if (parameters.Count > 0)
                cmd.Parameters.AddRange(parameters.ToArray());

        }
        #endregion

        #region 准备命令对象 -CommandBuilder(string cmdText, SqlCommand cmd, SqlConnection conn)
        /// <summary>
        /// 准备命令对象(执行无参存储过程)
        /// </summary>
        /// <param name="cmdText">存储过程名称</param>
        /// <param name="cmd">命令对象</param>
        /// <param name="conn">连接对象</param>
        private static void CommandBuilder(string cmdText, SqlCommand cmd, SqlConnection conn)
        {

            if (conn.State == System.Data.ConnectionState.Closed)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

        }
        #endregion

        #region 批插入 void BulkInsert( DataTable dt, string tableName, string connStr)
        /// <summary>
        /// 批插入 void BulkInsert( DataTable dt, string tableName, string connStr)
        /// </summary>
        /// <param name="dt">所有数据的表格</param>
        /// <param name="tableName">表名</param>
        public static int BulkInsert(DataTable dt, string tableName, string connStr)
        {
            int result = -1;
            if (string.IsNullOrEmpty(tableName))
                throw new Exception("请指定你要插入的表名");
            var count = dt.Rows.Count;
            if (count == 0)
                return result;
            SqlTransaction sqlBulkTran = null;
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    if (conn.State == System.Data.ConnectionState.Closed)
                        conn.Open();
                    sqlBulkTran = conn.BeginTransaction();
                    using (SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.CheckConstraints, sqlBulkTran))
                    {
                        copy.DestinationTableName = tableName;//指定目标表
                        copy.WriteToServer(dt);//将dt中的所有行复制到SqlBulkCopy对象的DestinationTableName指定的目标表中
                        if (sqlBulkTran != null)
                        {
                            sqlBulkTran.Commit();
                        }
                        result = 1;
                    }

                }

            }
            catch (Exception)
            {
                if (sqlBulkTran != null)
                {
                    sqlBulkTran.Rollback();
                }
            }
            finally
            {
                sqlBulkTran = null;
            }

            return result;
        }
        #endregion

    }
    #endregion
}
#region list 扩展方法 Author:高兵兵
public static class IListUtil
{
    /// <summary>
    /// 将集合类转换成DataTable
    /// </summary>
    /// <param name="list">集合</param>
    /// <returns></returns>
    public static DataTable AsDataTable<T>(this IList<T> list)
    {
        DataTable result = new DataTable();
        if (list.Count > 0)
        {
            PropertyInfo[] propertys = typeof(T).GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                result.Columns.Add(pi.Name, pi.PropertyType);
            }

            for (int i = 0; i < list.Count; i++)
            {
                ArrayList tempList = new ArrayList();
                foreach (var item in propertys)
                {
                    object obj = item.GetValue(list[i], null);
                    tempList.Add(obj);
                }

                object[] array = tempList.ToArray();
                result.LoadDataRow(array, true);
            }
        }
        return result;
    }

}
#endregion
时间: 2024-11-04 19:36:47

DBHelper数据库操作类(二)的相关文章

Android打造属于自己的数据库操作类。

1.概述 开发Android的同学都知道sdk已经为我们提供了一个SQLiteOpenHelper类来创建和管理SQLite数据库,通过写一个子类去继承它,就可以方便的创建.管理数据库.但是当我们需要去做增删改查的操作的时候,就得通过getWritableDatabase获取一个SQLiteDataBase然后老老实实去写操作值的put以及查询返回的Cursor处理,其实我们可以搞一个对象来帮我们干这些事情,打造属于你自己的数据库操作类. 2.操作类的初显形 假设现在我们什么都没有,我们要去搞一

PHP 数据库操作类:ezSQL

EZSQL类介绍: 下载地址:http://www.jb51.net/codes/26393.html ezsql是一个小型的快速的数据库操作类,可以让你很容易地用PHP操作各种数据库( MySQL.oracle8/9 .interbase.FireBird.PostgreSQL.MS-SQL.sqlite.sqlite C++). 在你的脚本开头是要包含一个一个PHP文件.然后,你就可以使用更小.更容易的一套ezsql函数来代替标准的PHP数据库函数. 它会自动缓存的查询结果,提供了一系列简单

php中mysql数据库操作类

talk less and show code: <?php/** *以下代码用于数据库操作类的封装* * @author rex<[email protected]> * @version 1.0* @since 2015*/ class Mysql{ //数据库连接返回值 private $conn; /*** [构造函数,返回值给$conn]* @param [string] $hostname [主机名]* @param [string] $username[用户名]* @par

我的DbHelper数据操作类(转)

其实,微软的企业库中有一个非常不错的数据操作类了.但是,不少公司(起码我遇到的几个...),对一些"封装"了些什么的东西不太敢用,虽然我推荐过微软的企业库框架了...但是还是要"评估"...一评就是几个月...而且,一些公司有的根本就是裸ado.net开发,或者自己封装的数据库操作类非常别扭,很不好用.      这里我给大家共享一个我参照企业库中的数据操作组件编码风格写的数据库操作类,对使用它的程序员来说,编码是很舒服滴(起码我觉得很好撒).以下是代码,很简单的,

PDO数据库操作类

1 <?php 2 include 'common_config.php'; 3 4 /** 5 * Class Mysql 6 * PDO数据库操作类 7 */ 8 class Mysql { 9 protected static $_dbh = null; //静态属性,所有数据库实例共用,避免重复连接数据库 10 protected $_dbType = DB_TYPE; 11 protected $_pconnect = false; //是否使用长连接 12 protected $_h

面向对象中数据库操作类

具体实现功能: 1.连接数据库: 2.插入数据: 3.更新数据: 4.删除数据' 5.修改数据: 6.求最大值: 7.求最小值: 8.求平均数: 9.求和: 10.指定查询: 具体代码分为三个部分: 一.config文件:主要用于连接数据库 <?php return array( 'DB_HOST' => '127.0.0.1',   //主机 'DB_USER' => 'root', //用户名 'DB_PWD' => '123456', //密码 'DB_NAME' =>

ASP.NET(C#) 数据库操作类 SqlServerDataBase

1 using System.Web.Security; 2 using System.Web.UI; 3 using System.Web.UI.WebControls; 4 using System.Web.UI.WebControls.WebParts; 5 using System.Web.UI.HtmlControls; 6 using System.Data.SqlClient; 7 8 namespace Mysqlserver 9 { 10 /// <summary> 11 /

【discuzX2】/source/class/class_core.php文件中数据库操作类DB及db_mysql分析

<?php /** * Discuz MySQL 类的支持 程序中一般不直接使用此类,而是使用DB类,DB类对db_mysql类中的方法又进行了二次封装 * */ class db_mysql { var $tablepre; var $version = ''; var $querynum = 0; var $slaveid = 0; var $curlink; var $link = array(); var $config = array(); var $sqldebug = array(

PHP单例模式的数据库操作类

自己练习写的单例模式的数据库操作类 1 <?php 2 //先建立单模:三私(私有变量.私有构造函数.私有的__clone函数)一公(公有方法),再封装连接数据库,以及返回结果 3 class MySQLDB{ 4 //定义连接数据库需要用到的私有属性 5 private $host; //主机id 6 private $port; //端口号 7 private $user; //用户 8 private $psw; //密码 9 private $dbname; //数据库名称 10 pri