基于SqlClient开发SQLServer工具类 伸手党的福音

注意:代码直接Copy调用即可,SQLServer工具类跟我上一个Oracle工具类有所不同,区别在于调用存储过程中是参数使用

/// <summary>
    ///基於.net( 向下兼容4.0)開發 SQLServerDBHelper工具類
    ///<para>作者: 害羞的青蛙</para>
    ///<para>時間: 2019-12-6</para>
    /// </summary>
    public static class SQLServerDBHelper
    {
        /// <summary>
        /// 執行SQL語句返回DataTable
        /// </summary>
        /// <param name="SQL">SQL語句</param>
        /// <param name="DBUrl">數據庫鏈接地址</param>
        /// <returns></returns>
        public static DataTable GetDataTableBySQL(string SQL, string DBUrl)
        {
            // 获取与数据库的连接对象並且绑定连接字符串
            SqlConnection conn = new SqlConnection(DBUrl);
            conn.Open();//打開資源
                        //获取数据库操作对象
            SqlCommand cmd = conn.CreateCommand();
            try
            {
                cmd.CommandText = SQL;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dataTable = new DataTable();
                dataTable.TableName = "數據集";
                adapter.Fill(dataTable);
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                return dataTable;
            }
            catch (Exception ex)
            {
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                throw ex;
            }
        }
        /// <summary>
        /// 執行非查詢的SQL語句
        /// </summary>
        /// <param name="SQL">SQL語句</param>
        /// <param name="DBUrl">數據庫鏈接地址</param>
        /// <returns></returns>
        public static int GetNonQueryBySQL(string SQL, string DBUrl)
        {
            // 获取与数据库的连接对象並且绑定连接字符串
            SqlConnection conn = new SqlConnection(DBUrl);
            conn.Open();//打開資源
                        //获取数据库操作对象
            SqlCommand cmd = conn.CreateCommand();
            try
            {
                cmd.CommandText = SQL;
                int num = cmd.ExecuteNonQuery();
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                return num;
            }
            catch (Exception ex)
            {
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                throw ex;
            }
        }
        /// <summary>
        /// 執行多條SQL語句,實現數據庫事務。
        /// </summary>
        /// <param name="SQLStringList">多條SQL語句</param>        
        /// <param name="BDUrl">數據庫鏈接地址</param>     
        public static int GetNonQueryByManySQL(ArrayList SQLStringList, string BDUrl)
        {
            using (SqlConnection conn = new SqlConnection(BDUrl))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int num = 0;
                    for (int i = 0; i < SQLStringList.Count; i++)
                    {
                        string SQL = SQLStringList[i].ToString();//獲取SQL語句
                        if (SQL.Trim().Length > 1)
                        {
                            cmd.CommandText = SQL;
                            num = cmd.ExecuteNonQuery();
                        }
                        tx.Commit();//提交事務
                        cmd.Dispose();//釋放資源
                        conn.Dispose();//釋放資源
                        conn.Close();//關閉

                    }
                    return num;//返回執行結果數量
                }
                catch (SqlException E)
                {
                    tx.Rollback();//事務回滾
                    throw new Exception(E.Message);
                }
            }
        }
        /// <summary>
        /// 調用存儲返回單個結果集
        /// <para>obj使用方法:new{ v_data=value, v_data1=value1}</para>
        /// <para>注意:obj中v_data為存儲參數名稱,value為對應的值,在SQLServer中沒有游標所以不需要定義輸出參數</para>
        /// </summary>
        /// <param name="storageName">存儲名稱</param>
        /// <param name="DBUrl">數據庫鏈接地址</param>
        /// <param name="obj">存儲參數對象</param>
        /// <returns></returns>
        public static DataTable GetDataTableByStorageName(string storageName, string DBUrl, object obj)
        {
            // 获取与数据库的连接对象並且绑定连接字符串
            SqlConnection conn = new SqlConnection(DBUrl);
            conn.Open();//打開資源
            //获取数据库操作对象
            SqlCommand cmd = conn.CreateCommand();
            try
            {
                cmd.CommandText = storageName;//存儲名稱
                cmd.CommandType = CommandType.StoredProcedure;
                PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);//獲取object中的字段名和值
                for (int i = 0; i < properties.Length; i++)
                {//設定輸入的類型和值
                        cmd.Parameters.Add(properties[i].Name, SqlDbType.NVarChar).Direction = ParameterDirection.Input;
                        cmd.Parameters[properties[i].Name].Value = properties[i].GetValue(obj, null);//賦值
                }
                DataTable dataTable = new DataTable();
                SqlDataAdapter oda = new SqlDataAdapter(cmd);
                oda.Fill(dataTable);
                dataTable.TableName = "數據集";
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                return dataTable;
            }
            catch (Exception ex)
            {
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                throw ex;
            }
        }
        /// <summary>
        /// 調用存儲返回String字符串信息(最後一個位置必須為String類型字符,位置不能顛倒)
        /// <para>obj使用方法:new{ v_data=value, v_data1=value1,out_string=""}</para>
        /// <para>注意:obj中v_data為存儲參數名稱,value為對應的值,out_string為輸出參數不需要輸入值</para>
        /// </summary>
        /// <param name="storageName"></param>
        /// <param name="DBUrl"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetStringDataByStorageName(string storageName, string DBUrl, object obj)
        {
            SqlConnection conn = new SqlConnection(DBUrl);
            conn.Open();
            //获取数据库操作对象
            SqlCommand cmd = conn.CreateCommand();
            try
            {
                cmd.CommandText = storageName;//存儲名稱
                cmd.CommandType = CommandType.StoredProcedure;
                PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);//獲取object中的字段名和值
                for (int i = 0; i < properties.Length; i++)
                {
                    if (i == (properties.Length - 1))
                    { //設定輸出的類型和值
                        cmd.Parameters.Add("@" + properties[i].Name, SqlDbType.NVarChar, short.MaxValue).Direction = ParameterDirection.Output;
                        cmd.Parameters["@" + properties[i].Name].Value = DBNull.Value;//賦值
                    }
                    else
                    {//設定輸入的類型和值
                        cmd.Parameters.Add("@" + properties[i].Name, SqlDbType.NVarChar).Direction = ParameterDirection.Input;
                        cmd.Parameters["@" + properties[i].Name].Value = properties[i].GetValue(obj, null);//賦值
                    }
                }
                cmd.ExecuteNonQuery();
                string message = cmd.Parameters["@" + properties[properties.Length - 1].Name].Value.ToString();//獲取返回的值
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                return message;
            }
            catch (Exception ex)
            {
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                throw ex;
            }
        }
        /// <summary>
        /// 調用存儲返回String字符串信息和DataTable數據表格(最後一個為輸出字符串,位置不能顛倒)
        /// <para>obj使用方法:new{ v_data=value, v_data1=value1,out_string=""}</para>
        /// <para>注意:obj中v_data為存儲參數名稱,value為對應的值,out_string為輸出參數不需要輸入值, 在SQLServer中沒有游標所以不需要定義輸出參數</para>
        /// </summary>
        /// <param name="storageName">存儲名稱</param>
        /// <param name="DBUrl">數據庫鏈接地址</param>
        /// <param name="obj">存儲參數對象</param>
        /// <param name="dataTable">返回結果集</param>
        /// <returns></returns>
        public static string GetStringAndDataTableByStorageName(string storageName, string DBUrl, object obj, out DataTable dataTable)
        {
            // 获取与数据库的连接对象並且绑定连接字符串
            SqlConnection conn = new SqlConnection(DBUrl);
            conn.Open();//打開資源
            //获取数据库操作对象
            SqlCommand cmd = conn.CreateCommand();
            try
            {
                cmd.CommandText = storageName;//存儲名稱
                cmd.CommandType = CommandType.StoredProcedure;
                PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);//獲取object中的字段名和值
                for (int i = 0; i < properties.Length; i++)
                {
                    if (i == (properties.Length - 1))
                    {//設定輸出的類型和值
                        cmd.Parameters.Add(properties[i].Name, SqlDbType.NVarChar, short.MaxValue).Direction = ParameterDirection.Output;
                        cmd.Parameters[properties[i].Name].Value = DBNull.Value;//賦值
                    }
                    else
                    {//設定輸入的類型和值
                        cmd.Parameters.Add(properties[i].Name, SqlDbType.NVarChar).Direction = ParameterDirection.Input;
                        cmd.Parameters[properties[i].Name].Value = properties[i].GetValue(obj, null);//賦值
                    }
                }
                DataTable dt = new DataTable();
                SqlDataAdapter oda = new SqlDataAdapter(cmd);
                oda.Fill(dt);
                dt.TableName = "數據集";
                dataTable = dt;//返回數據結果集
                string message = cmd.Parameters[properties[properties.Length - 1].Name].Value.ToString();//獲取輸出的字符串
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                return message;
            }
            catch (Exception ex)
            {
                cmd.Dispose();//釋放資源
                conn.Dispose();//釋放資源
                conn.Close();//關閉
                throw ex;
            }
        }
    }

  

猜你喜欢

转载自www.cnblogs.com/ShyFrog/p/12000353.html