kenchell

导航

 
 

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.SqlClient;

using System.Configuration;

using System.Data;

using System.Collections;

 

namespace DataBaseHelp

{

    /// <summary>

    /// 数据访问抽象基础类

    /// Copyright (C) 2009 By Zhuangyq

    /// </summary>

    public abstract class DbHelperSQL

    {

        #region fields

        //public static string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

        //public static string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];

        public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        #endregion

 

        #region constructor

        public DbHelperSQL()

        { }

        #endregion

 

        #region 执行简单SQL语句

        #region ExecuteSql

        /// <summary>

        /// 执行SQL语句,返回受影响的记录数

        /// </summary>

        /// <param name="SQLString">SQL语句</param>

        /// 一般用于增、删、改,而不用于查询,因为如果是查询受影响的行数返回为-1

        /// <returns>影响的记录数</returns>

        public static int ExecuteSql(string SQLString)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();                      

                        int rows = cmd.ExecuteNonQuery();

                        return rows;

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

        #endregion

 

        #region ExecuteSqlByTime

        public static int ExecuteSqlByTime(string SQLString, int Times)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd= new SqlCommand(SQLString,connection))

                {

                    try

                    {

                        connection.Open();

                        cmd.CommandTimeout = Times;

                        int rows = cmd.ExecuteNonQuery();

                        return rows;

                    }

                    catch (SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

        #endregion

 

        #region ExecuteSqlTran

        /// <summary>

        /// 执行多条SQL语句,实现数据事务

        /// </summary>

        /// List<string> lists = new List<string>();

        /// lists.Add("UPDATE course SET fenshu = '130' WHERE id =22");

        /// lists.Add("UPDATE course SET fenshu = '130' WHERE id =23");

        /// lists.Add("UPDATE course SET fenshu = '130' WHERE id =24");

        /// lists.Add("SELECT * FROM course");

        /// 以上执行结果,受影响的行数,最后返回为2,因为SELECT * FROM course,受影响到行数值为-1

        /// <param name="SQLStringList"></param>

        /// <returns></returns>

        public static int ExecuteSqlTran(List<string> SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand();

                cmd.Connection = conn;

                SqlTransaction tx = conn.BeginTransaction();

                cmd.Transaction = tx;

                try

                {

                    int count = 0;

                    for (int i = 0; i < SQLStringList.Count; i++)

                    {

                        string strsql = SQLStringList[i];

                        if (strsql.Trim().Length > 1)

                        {

                            cmd.CommandText = strsql;

                            count += cmd.ExecuteNonQuery();

                        }

                    }

                    tx.Commit();

                    return count;

                }

                catch

                {

                    tx.Rollback();

                    return 0;

                }

            }

        }

        #endregion

 

        #region 带@content参数的SQL语句

        #region ExecuteSql

        /// <summary>

        /// 执行带参数的SQL语句

        /// </summary>

        /// <param name="SQLString">执行的SQL语句</param>

        /// <param name="content">参数的值</param>

        /// 对于增、删、改语句:

        /// DbHelperSQL.ExecuteSql("insert into course values(@CONTENT,'语文',120)", "kencell22");

        /// DbHelperSQL.ExecuteSql("delete from course where name = @CONTENT", "kencell");

       /// DbHelperSQL.ExecuteSql("update course set name = @CONTENT where id = 26", "xiaozhuang");

        /// 以上三句在执行cmd.ExecuteNonQuery();语句时,才对数据库操作。此时返回的为此三种操作的受影响的行数。

        /// 只有执行DbHelperSQL.ExecuteSql("select * From course where name = @content", "kencell");语句时,rows不是返回受影响的行数,而是-1

        /// @CONTENT可以是小写也可以是大写,但是参数名称一定要一致@CONTENTX就会报错

        /// <returns>受影响的行数</returns>

        public static int ExecuteSql(string SQLString, string content)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand(SQLString, conn);

                System.Data.SqlClient.SqlParameter myparameter = new SqlParameter("@content", SqlDbType.VarChar);

                myparameter.Value = content;

                cmd.Parameters.Add(myparameter);

                try

                {

                    conn.Open();

                    int rows = cmd.ExecuteNonQuery();

                    return rows;

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    throw e;

                }

                finally

                {

                    cmd.Dispose();

                    conn.Close();

                }

            }

        }

        #endregion

 

        #region ExecuteSqlGet

        public static object ExecuteSqlGet(string SQLString, string content)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand(SQLString, conn);

                System.Data.SqlClient.SqlParameter myparameter = new SqlParameter("@content", SqlDbType.NText);

                myparameter.Value = content;

                cmd.Parameters.Add(myparameter);

                try

                {

                    conn.Open();

                    object obj = cmd.ExecuteScalar();

                    if (Object.Equals(obj, null) || Object.Equals(obj, DBNull.Value))

                    {

                        return null;

                    }

                    else

                    {

                        return obj;

                    }

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    throw e;

                }

                finally

                {

                    cmd.Dispose();

                    conn.Close();

                }

            }

        }

        #endregion

        #endregion

 

        #region GetSingle

        /// <summary>

        /// 执行一条计算查询结果语句,返回查询结果(object)。

        /// </summary>

        /// <param name="SQLString">计算查询结果语句</param>

        /// 对于增、删、改语句:

        /// insert into course values('zhuangyq','语文',80)

        /// delete from course where id = 28

        /// update course set fenshu = '102' where id = 26

        /// 以上三句在执行cmd.ExecuteScalar();语句时,才对数据库操作。此时返回的obj为nul

        /// 只有执行select * From course语句时,obj为查询所返回的结果集中的第一行的第一列

        /// <returns>查询结果(object)</returns>

        public static object GetSingle(string SQLString)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();

                        object obj = cmd.ExecuteScalar();

                        if (object.Equals(obj, null) || object.Equals(obj, System.DBNull.Value))

                        {

                            return null;

                        }

                        else

                        {

                            return obj;

                        }

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

        #endregion   

       

        #region ExecuteReader

        /// <summary>

        /// 执行查询语句,返回DataSet

        /// </summary>

        /// <param name="SQLString">查询语句</param>

        /// 对于增、删、改语句:

        /// insert into course values('zhuangyq','语文',80)

        /// delete from course where id = 28

        /// update course set fenshu = '102' where id = 26

        /// 以上三句在执行cmd.ExecuteReader(CommandBehavior.CloseConnection)语句时,才对数据库操作。此时返回的myReader的GetSchemaTable()为null,不存在表

        /// 只有执行select * From course语句时,返回的myReader的GetSchemaTable()表才不为空,此时可以把改myReader转化为DataTable

        /// <returns></returns>

        public static SqlDataReader ExecuteReader(string SQLString)

        {

            //using (SqlConnection conn = new SqlConnection(connectionString))

            //{

            //    using (SqlCommand cmd = new SqlCommand(SQLString, conn))

            //    {

            //        try

            //        {

            //            conn.Open();

            //            SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            //            return myReader;

            //        }

            //        catch (System.Data.SqlClient.SqlException e)

            //        {

            //            conn.Close();

            //            throw e;

            //        }

            //    }

            //}

            //千万不要像上面那样写,不然调用conn.Dispose()对象,导致连接关闭,那么就不能使用myReader

            //SqlDataReader 只能在保持跟数据库连接的状态下才可以读取

            SqlConnection conn = new SqlConnection(connectionString);

 

            SqlCommand cmd = new SqlCommand(SQLString, conn);

            try

            {

                conn.Open();

                //给cmd.ExecuteReader加上参数CommandBehavior.CloseConnection会在cmd.ExecuteReader执行完后自动关闭与之相关联的conn

                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                return myReader;

            }

            catch (SqlException e)

            {

                conn.Close();

                throw e;

            }

            //也千万不要加上如下语句,否则

            //finally

            //{

            //    cmd.Dispose();

            //    conn.Close();               

            //}         

        }

        #endregion

 

        #region Query

        /// <summary>

        /// 执行查询语句,返回DataSet

        /// </summary>

        /// <param name="SQLString">查询语句</param>

        /// 对于增、删、改语句:

        /// insert into course values('zhuangyq','语文',80)

        /// delete from course where id = 27

        /// update course set fenshu = '100' where id = 26

        /// 以上三句在执行datpter.Fill(ds, "Table1")语句时,才对数据库操作,此时返回的ds对象不存在任何表

        /// 只有执行select * From course语句时,返回的DataSet才有表,表名为:Table1

        /// SqlDataAdapter 大多情况下是一次性读取一个表,然后填充到DataSet中,然后就可以断开跟数据库的连接了。

        /// <returns>DataSet</returns>

        public static DataSet Query(string SQLString)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                DataSet ds = new DataSet();

                try

                {

                    conn.Open();

                    SqlDataAdapter datpter = new SqlDataAdapter(SQLString, conn);                   

                    datpter.Fill(ds, "Table1");

                    return ds;

                }

                catch (SqlException e)

                {

                    conn.Close();

                    throw e;

                }

            }

        }

        #endregion

        #endregion

 

        #region 执行带参数的SQL语句

        #region PrepareCommand

        private static void PrepareCommand(SqlCommand cmd,SqlConnection conn,SqlTransaction trans,string cmdText,SqlParameter[] cmdParms)

        {

            if (conn.State != ConnectionState.Open)

                conn.Open();

            cmd.Connection = conn;

            cmd.CommandText = cmdText;

            if (trans != null)

                cmd.Transaction = trans;

            cmd.CommandType = CommandType.Text;

            if (cmdParms != null)

            {

                foreach (SqlParameter parameter in cmdParms)

                {

                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))

                    {

                        parameter.Value = DBNull.Value;

                    }

                    cmd.Parameters.Add(parameter);

                }

            }

        }

        #endregion

 

        #region ExecuteSql

        /// <summary>

        /// 执行SQL语句,返回影响的记录数

        /// </summary>

        /// <param name="SQLString">SQL语句</param>

        /// <param name="cmdParms">受影响的行数</param>

        /// 执行实例一(输入参数):

        /// SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@FENSHU", SqlDbType.Int),

        ///                                             new SqlParameter("@KECHENG",SqlDbType.VarChar)};

        ///       parms[0].Value = 77;

        ///       parms[1].Value = "物理";

        ///       int count = DbHelperSQL.ExecuteSql("update course set fenshu = @fenshu,kecheng = @kecheng where id = 26", parms);

        /// 执行实例二(输出参数):

        /// SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@total", SqlDbType.Int),

        ///                                             new SqlParameter("@rows",SqlDbType.Int)};

        ///        parms[0].Direction = ParameterDirection.Output;

        ///        parms[1].Direction = ParameterDirection.Output;

        ///        int affect = DbHelperSQL.ExecuteSql("select @total = sum(fenshu),@rows=count(1) from course", parms);

        ///        int total = Convert.ToInt32(parms[0].Value);

        ///        int rows = Convert.ToInt32(parms[1].Value);

        /// <returns></returns>

        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    try

                    {

                        PrepareCommand(cmd, conn, null, SQLString, cmdParms);

                        int rows = cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();

                        return rows;

                    }

                    catch(SqlException e)

                    {

                        throw e;

                    }

                }

            }

        }      

        #endregion

 

        #region ExecuteSqlTran

        /// <summary>

        /// 执行多条SQL语句,实现数据库事务。

        /// </summary>

        ///   Hashtable hs = new Hashtable();             

        ///   SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@FENSHU", SqlDbType.Int),

        ///                                                     new SqlParameter("@KECHENG",SqlDbType.VarChar)};

        ///     parms[0].Value = 112;

        ///     parms[1].Value = "历史";

        ///   SqlParameter[] parms1 = new SqlParameter[] { new SqlParameter("@NAME", SqlDbType.VarChar),

        ///                                                     new SqlParameter("@FENSHU", SqlDbType.Int),

        ///                                                     new SqlParameter("@KECHENG",SqlDbType.VarChar)};

        ///     parms1[0].Value = "kenchell";

        ///     parms1[1].Value = 123;

        ///     parms1[2].Value = "生物";

        ///     hs.Add("update course set fenshu = @fenshu,kecheng = @kecheng where id = 26", parms);

        ///     hs.Add("insert into course(name,fenshu,kecheng) values (@name,@fenshu,@kecheng)", parms1);

        ///     DbHelperSQL.ExecuteSqlTran(hs);

        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>

        public static void ExecuteSqlTran(Hashtable SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                using (SqlTransaction trans = conn.BeginTransaction())

                {

                    SqlCommand cmd = new SqlCommand();

                    try

                    {

                        foreach (DictionaryEntry myDE in SQLStringList)

                        {

                            string cmdText = myDE.Key.ToString();

                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;

                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            int val = cmd.ExecuteNonQuery();

                            cmd.Parameters.Clear();//记得清除参数

                        }

                        trans.Commit();

                    }

                    catch(SqlException ex)

                    {

                        trans.Rollback();

                        throw ex;

                    }

                }

            }

        }

        #endregion

      

        #region ExecuteReader

        /// <summary>

        /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )

        /// </summary>

        /// <param name="strSQL">查询语句</param>

        /// <returns>SqlDataReader</returns>

        public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)

        {

            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand cmd = new SqlCommand();

            try

            {

                PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Parameters.Clear();

                return myReader;

            }

            catch (System.Data.SqlClient.SqlException e)

            {

                connection.Close();

                throw e;

            }

            //finally

            //{

            //    cmd.Dispose();

            //    connection.Close();

            //}

        }

        #endregion

 

        #region Query

        /// <summary>

        /// 执行查询语句,返回DataSet

        /// </summary>

        /// SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@KECHENG",SqlDbType.VarChar)};

        ///     parms[0].Value = "语文";

        ///     DataSet ds = DbHelperSQL.Query("select * From course where kecheng = @kecheng", parms);

        /// <param name="SQLString">查询语句</param>

        /// <returns>DataSet</returns>

        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand();

                PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))

                {

                    DataSet ds = new DataSet();

                    try

                    {

                        da.Fill(ds, "Table1");

                        cmd.Parameters.Clear();

                    }

                    catch (System.Data.SqlClient.SqlException ex)

                    {

                        throw new Exception(ex.Message);

                    }

                    return ds;

                }

            }

        }

        #endregion

        #endregion

 

        #region 执行存储过程操作

        #region BuildQueryCommand

        private static SqlCommand BuildQueryCommand(SqlConnection conn, string storedProcName, IDataParameter[] parameters)

        {

            SqlCommand cmd = new SqlCommand(storedProcName, conn);

            cmd.CommandType = CommandType.StoredProcedure;

            foreach (SqlParameter parameter in parameters)

            {

                if (parameter != null)

                {

                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&

                        (parameter.Value == null))

                    {

                        parameter.Value = DBNull.Value;

                    }

                    cmd.Parameters.Add(parameter);

                }

            }

            return cmd;

        }

        #endregion

 

        #region RunProcedure

        /// <summary>

        /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )

        /// </summary>

        /// <param name="storedProcName">存储过程名</param>

        /// <param name="parameters">存储过程参数</param>

        /// 存储过程:

        /// ALTER PROC [dbo].[SP_QueryData]

        /// (

        /// @kecheng varchar(20),

        /// @COUNT INT OUTPUT

        /// )

        /// AS

        /// BEGIN

        /// SELECT * FROM COURSE WHERE kecheng = @kecheng //如果有多个的查询语句,则返回第一个查询语句的SqlDataReader

        /// SELECT @COUNT = COUNT(1) FROM COURSE

        /// END  

        /// 客户端代码:

        /// try

        /// {

        ///    SqlParameter[] parms = new SqlParameter[]{new SqlParameter("@Kecheng",SqlDbType.VarChar),

        ///                                              new SqlParameter("@COUNT",SqlDbType.Int)};

        ///    parms[0].Value = "语文";

        ///    parms[1].Direction = ParameterDirection.Output;

        ///    SqlDataReader reader = DbHelperSQL.RunProcedure("SP_QUERYDATA", parms);

        ///    DataTable dt = ConvertDataReaderToDataTable(reader);

        ///    this.dataGridView1.DataSource = dt;

        ///    int count = Convert.ToInt32(parms[1].Value);

        /// }

        /// catch (Exception ex)

        ///

        ///    MessageBox.Show(ex.Message);

        /// }

        /// <returns></returns>

        public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)

        {

            SqlConnection conn = new SqlConnection(connectionString);

            conn.Open();

            SqlCommand cmd = BuildQueryCommand(conn, storedProcName, parameters);

            //cmd.CommandType = CommandType.StoredProcedure;

            SqlDataReader returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            return returnReader;

        }

        #endregion   

 

        #region RunProcedure

        /// <summary>

        /// 执行存储过程

        /// </summary>

        /// <param name="storedProcName">存储过程名</param>

        /// <param name="parameters">存储过程参数</param>

        /// <param name="tableName">表名</param>

        /// ALTER PROC [DBO].[SP_QUERYDATA]

        /// (

        ///  @KECHENG VARCHAR(20),

        /// @COUNT INT OUTPUT

        /// )

        /// AS

        /// BEGIN

        /// SELECT * FROM STUDENT

        /// SELECT * FROM COURSE WHERE KECHENG = @KECHENG

        /// SELECT * FROM CATEGORY

        /// SELECT @COUNT = COUNT(1) FROM COURSE

        /// END

        /// try

        /// {

        ///     SqlParameter[] parms = new SqlParameter[]{new SqlParameter("@Kecheng",SqlDbType.VarChar),

        ///                                               new SqlParameter("@COUNT",SqlDbType.Int)};

        ///     parms[0].Value = "语文";

        ///     parms[1].Direction = ParameterDirection.Output;

        ///     DataSet ds = DbHelperSQL.RunProcedure("SP_QUERYDATA", parms,"MyTable");//整个ds返回3张表,每张表的表名为分别为MyTable、MyTable1、MyTable2

        ///     this.dataGridView1.DataSource = ds.Tables[0];

        ///     int count = Convert.ToInt32(parms[1].Value);

        /// }

        /// catch (Exception ex)

        /// {

        ///     MessageBox.Show(ex.Message);

        /// }

        /// <returns>DataSet结果中的表名</returns>

        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                DataSet ds = new DataSet();

                conn.Open();

                SqlDataAdapter dataAdap = new SqlDataAdapter();

                dataAdap.SelectCommand = BuildQueryCommand(conn,storedProcName,parameters);

                dataAdap.Fill(ds, tableName);

                conn.Close();

                return ds;

            }

        }

        #endregion

 

        #region RunProcedure

        /// <summary>

        /// 执行存储过程

        /// </summary>

        /// <param name="storedProcName">存储过程名</param>

        /// <param name="parameters">参数</param>

        /// <param name="RowsAffected">受影响的行数</param>

        /// ALTER PROC [DBO].[SP_QUERYDATA]

        /// (

        /// @KECHENG VARCHAR(20),

        /// @COUNT INT OUTPUT

        /// )

        /// AS

        /// BEGIN

        /// SELECT * FROM STUDENT

        /// SELECT * FROM COURSE WHERE KECHENG = @KECHENG

        /// SELECT * FROM CATEGORY

        /// update STUDENT set 分数 = 99 where 科目='数学'

        /// SELECT @COUNT = COUNT(1) FROM COURSE

        /// insert into STUDENT select '语文',88,'hello'

        /// insert into STUDENT select '语文',89,'hello'

        /// delete from COURSE where id= 35

        /// return 78;

        /// END

        /// <returns>存储过程return的值</returns>

        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int RowsAffected)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                int result;

                conn.Open();

                SqlCommand cmd = BuildQueryCommand(conn, storedProcName, parameters);

                cmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue,

                    false,0,0,string.Empty,DataRowVersion.Default,null));

                RowsAffected = cmd.ExecuteNonQuery();//返回存储过程中增、删、改等受影响的行数之和

                result = (int)cmd.Parameters["ReturnValue"].Value; //存储过程的返回值

                return result;

            }

        }

        #endregion

        #endregion

    }

}

 

posted on 2009-01-11 00:25  kenchell  阅读(803)  评论(0编辑  收藏  举报