SqlHelper

来源:https://www.cnblogs.com/lgq880821/archive/2019/09/12/11510822.html
-Advertisement-
Play Games

using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Linq;using System. ...


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MZ.Models.DAL
{

    //可更改為MySql


    public class SqlHelper
    {
        #region Fields

        private string connectString = ConfigurationManager.ConnectionStrings["connstr"].ToString();

        #endregion

        #region Constructors

        public SqlHelper()
        {

        }

        public SqlHelper(string connectString)
        {
            this.connectString = connectString;
        }

        #endregion

        #region Property ConnectionString

        public string ConnectionString
        {
            get { return this.connectString; }
        }

        #endregion

        #region Method ExecuteNonQuery

        public int ExecuteNonQuery(string commandText)
        {
            return this.ExecuteNonQuery(commandText, CommandType.Text, null);
        }

        public int ExecuteNonQuery(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteNonQuery(commandText, CommandType.Text, paras);
        }

        public int ExecuteNonQuery(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            int result = 0;
            using (SqlConnection connection = new SqlConnection(this.connectString))
            {
                connection.Open();
                result = this.ExecuteNonQuery(commandText, commandType, paras, connection);
                connection.Close();
            }

            return result;
        }

        public int ExecuteNonQuery(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            int result = command.ExecuteNonQuery();
            command.Dispose();

            return result;
        }

        public int ExecuteNonQuery(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            int result = command.ExecuteNonQuery();
            command.Dispose();

            return result;
        }

        #endregion

        #region Method ExecuteScalar

        public int ExecuteScalar(string commandText)
        {
            return this.ExecuteScalar(commandText, CommandType.Text, null);
        }

        public int ExecuteScalar(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteScalar(commandText, CommandType.Text, paras);
        }

        public int ExecuteScalar(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            int result = 0;
            using (SqlConnection connection = new SqlConnection(this.connectString))
            {
                connection.Open();
                result = ExecuteScalar(commandText, commandType, paras, connection);
                connection.Close();
            }

            return result;
        }

        public int ExecuteScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null || result + "" == "")
                return 0;

            return Convert.ToInt32(result);
        }

        public int ExecuteScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null)
                return 0;

            return (int)result;
        }

        #endregion

        #region Method ExecuteObjectScalar

        public object ExecuteObjectScalar(string commandText)
        {
            return this.ExecuteObjectScalar(commandText, CommandType.Text, null);
        }

        public object ExecuteObjectScalar(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteObjectScalar(commandText, CommandType.Text, paras);
        }

        public object ExecuteObjectScalar(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            object result;
            using (SqlConnection connection = new SqlConnection(this.connectString))
            {
                connection.Open();
                result = ExecuteObjectScalar(commandText, commandType, paras, connection);
                connection.Close();
            }

            return result;
        }

        public object ExecuteObjectScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null || result + "" == "")
                return null;

            return result;
        }

        public object ExecuteObjectScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null)
                return null;

            return result;
        }

        #endregion

        #region Method ExecuteStringScalar

        public string ExecuteStringScalar(string commandText)
        {
            return this.ExecuteStringScalar(commandText, CommandType.Text, null);
        }

        public string ExecuteStringScalar(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteStringScalar(commandText, CommandType.Text, paras);
        }

        public string ExecuteStringScalar(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            string result = "";
            using (SqlConnection connection = new SqlConnection(this.connectString))
            {
                connection.Open();
                result = ExecuteStringScalar(commandText, commandType, paras, connection);
                connection.Close();
            }

            return result;
        }

        public string ExecuteStringScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null)
                return "";

            return result.ToString();
        }

        public string ExecuteStringScalar(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            object result = command.ExecuteScalar();
            command.Dispose();

            if (result == null)
                return "";

            return result.ToString();
        }

        #endregion

        #region Method ExecuteDataTable

        public DataTable ExecuteDataTable(string commandText)
        {
            return this.ExecuteDataTable(commandText, CommandType.Text, null);
        }

        public DataTable ExecuteDataTable(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteDataTable(commandText, CommandType.Text, paras);
        }

        public DataTable ExecuteDataTable(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            DataTable dt = null;
            using (SqlConnection connection = new SqlConnection(this.connectString))
            {
                connection.Open();
                dt = this.ExecuteDataTable(commandText, commandType, paras, connection);
                connection.Close();
            }

            return dt;
        }

        public DataTable ExecuteDataTable(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            DataTable dt = new DataTable();
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(dt);
            command.Dispose();
            adapter.Dispose();

            return dt;
        }

        public DataTable ExecuteDataTable(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            DataTable dt = new DataTable();
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(dt);
            command.Dispose();
            adapter.Dispose();

            return dt;
        }

        #endregion

        #region Method ExecuteDataSet

        public DataSet ExecuteDataSet(string commandText)
        {
            return this.ExecuteDataSet(commandText, CommandType.Text, null);
        }

        public DataSet ExecuteDataSet(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteDataSet(commandText, CommandType.Text, paras);
        }

        public DataSet ExecuteDataSet(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            DataSet ds = null;
            using (SqlConnection connection = new SqlConnection(connectString))
            {
                connection.Open();
                ds = this.ExecuteDataSet(commandText, commandType, paras, connection);
                connection.Close();
            }

            return ds;
        }

        public DataSet ExecuteDataSet(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            DataSet ds = new DataSet();
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);
            command.Dispose();
            adapter.Dispose();

            return ds;
        }

        public DataSet ExecuteDataSet(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            DataSet ds = new DataSet();
            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);
            command.Dispose();
            adapter.Dispose();

            return ds;
        }

        #endregion

        #region Method ExecuteEntity
        private static T ExecuteDataReader<T>(SqlDataReader dr)
        {
            T obj = default(T);
            Type type = typeof(T);
            PropertyInfo[] propertyInfos = type.GetProperties();
            int columnCount = dr.FieldCount;
            obj = Activator.CreateInstance<T>();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                string propertyName = propertyInfo.Name;
                for (int i = 0; i < columnCount; i++)
                {
                    string columnName = dr.GetName(i);
                    if (string.Compare(propertyName, columnName, true) == 0)
                    {
                        object value = dr.GetValue(i);
                        if (value != null && value != DBNull.Value)
                        {
                            propertyInfo.SetValue(obj, value, null);
                        }
                        break;
                    }
                }
            }
            return obj;
        }

        public T ExecuteEntity<T>(string commandText)
        {
            return this.ExecuteEntity<T>(commandText, CommandType.Text, null);
        }

        public T ExecuteEntity<T>(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteEntity<T>(commandText, CommandType.Text, paras);
        }

        public T ExecuteEntity<T>(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            T obj = default(T);
            using (SqlConnection connection = new SqlConnection(connectString))
            {
                connection.Open();
                obj = this.ExecuteEntity<T>(commandText, commandType, paras, connection);
                connection.Close();
            }

            return obj;
        }

        public T ExecuteEntity<T>(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            T obj = default(T);
            using (SqlCommand cmd = new SqlCommand(commandText, connection))
            {
                cmd.CommandType = commandType;
                if(paras!=null)
                cmd.Parameters.AddRange(paras);
                connection.Close();
                connection.Open();
                using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    while (dr.Read())
                    {
                        obj = ExecuteDataReader<T>(dr);
                        break;
                    }
                }
            }
            return obj;
        }
        #endregion

        #region Method ExecuteList
        public List<T> ExecuteList<T>(string commandText)
        {
            return this.ExecuteList<T>(commandText, CommandType.Text, null);
        }

        public List<T> ExecuteList<T>(string commandText, SqlParameter[] paras)
        {
            return this.ExecuteList<T>(commandText, CommandType.Text, paras);
        }

        public List<T> ExecuteList<T>(string commandText, CommandType commandType, SqlParameter[] paras)
        {
            List<T> list = new List<T>();
            using (SqlConnection connection = new SqlConnection(connectString))
            {
                connection.Open();
                list = this.ExecuteList<T>(commandText, commandType, paras, connection);
                connection.Close();
            }

            return list;

        }

        public List<T> ExecuteList<T>(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            List<T> list = new List<T>();

            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, connection);
            using (SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (dr.Read())
                {
                    T obj = ExecuteDataReader<T>(dr);
                    list.Add(obj);
                }
            }
            command.Dispose();

            return list;
        }

        public List<T> ExecuteList<T>(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            List<T> list = new List<T>();

            SqlCommand command = this.CreateCommandHelper(commandText, commandType, paras, trans);
            using (SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (dr.Read())
                {
                    T obj = ExecuteDataReader<T>(dr);
                    list.Add(obj);
                }
            }
            command.Dispose();

            return list;
        }
        #endregion

        #region Method InsertBatch

        public int InsertBatch(string commandText, DataTable data, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = this.CreateCommandHelper(commandText, CommandType.Text, paras, trans);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.InsertCommand = command;
            int result = adapter.Update(data);

            adapter.Dispose();
            command.Dispose();

            return result;
        }

        #endregion

        #region Private Method CreateCommandHelper

        private SqlCommand CreateCommandHelper(string commandText, CommandType commandType, SqlParameter[] paras, SqlConnection connection)
        {
            SqlCommand command = new SqlCommand();
            command.CommandText = commandText;
            command.CommandType = commandType;
            command.Connection = connection;

            if (paras != null && paras.Length > 0)
            {
                foreach (SqlParameter p in paras)
                {
                    /*Update 修改無法使用 ParameterDirection.Output 來輸出值的Bug*/
                    //SqlParameter paraNew = new SqlParameter();
                    if (p != null)
                    {
                        // Check for derived output value with no value assigned
                        if ((p.Direction == ParameterDirection.InputOutput ||
                            p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        /*
                        paraNew.ParameterName = p.ParameterName;
                        paraNew.SqlDbType = p.SqlDbType;
                        paraNew.DbType = p.DbType;
                        paraNew.SourceColumn = p.SourceColumn;
                        paraNew.Value = p.Value;
                         */

                        command.Parameters.Add(p);
                    }

                }
            }

            return command;
        }

        private SqlCommand CreateCommandHelper(string commandText, CommandType commandType, SqlParameter[] paras, SqlTransaction trans)
        {
            SqlCommand command = new SqlCommand();
            command.CommandText = commandText;
            command.CommandType = commandType;
            command.Connection = trans.Connection;
            command.Transaction = trans;

            if (paras != null && paras.Length > 0)
            {
                foreach (SqlParameter p in paras)
                {
                    SqlParameter paraNew = new SqlParameter();
                    if (p != null)
                    {
                        // Check for derived output value with no value assigned
                        if ((p.Direction == ParameterDirection.InputOutput ||
                            p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }

                        paraNew.ParameterName = p.ParameterName;
                        paraNew.SqlDbType = p.SqlDbType;
                        paraNew.DbType = p.DbType;
                        paraNew.SourceColumn = p.SourceColumn;
                        paraNew.Value = p.Value;
                    }
                    command.Parameters.Add(paraNew);
                }
            }

            return command;
        }

        #endregion
    }
}


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 有時候我們調試location指令時希望location指令能夠直接輸出文本,這樣能夠方便我們進行調試。這時我們可以使用echo模塊實現,但是大多數情況我們沒有安裝這個模塊,那麼我們還可以使用另一個方法來實現這個想法 直接返迴文本 html標簽格式 返回json文本 ...
  • 項目環境搭建 一、創建django項目 1.創建python虛擬環境 在虛擬機上創建python虛擬環境,因為實際項目部署,實在linux 2.創建django項目 1.安裝django 選擇安裝django2.1.x最新的一個版本2.1.10 2.創建django項目 3.創建pycharm項目 ...
  • .NET Core針對緩存提供了很好的支持 ,我們不僅可以選擇將數據緩存在應用進程自身的記憶體中,還可以採用分散式的形式將緩存數據存儲在一個“中心資料庫”中。對於分散式緩存,.NET Core提供了針對Redis和SQL Server的原生支持。除了這個獨立的緩存系統之外,ASP.NET Core還借... ...
  • 無論ViewResult還是JsonResult都繼承ActionResult,ActionResult里只有一個方法ExecuteResult 1、Controllr的Json方法 實際上是new JsonResult,然後執行ExecuteResult方法,指定了ContentType-appl ...
  • 場景 在Winform中需要存儲某控制項的Color屬性,存儲的是string字元串, 然後再對控制項進行賦值時需要將string轉換成Color。 實現 ...
  • C# 獲取指定類型的文件 public static List<FileInfo> getFile(string path, string extName) { List<FileInfo> lst = new List<FileInfo>(); try { string[] dir = Direc ...
  • 前提 入行已經7,8年了,一直想做一套漂亮點的自定義控制項,於是就有了本系列文章。 GitHub:https://github.com/kwwwvagaa/NetWinformControl 碼雲:https://gitee.com/kwwwvagaa/net_winform_custom_contr ...
  • 一、框架簡介 此框架是針對於webapi進行開發,項目分層是基於ABP框架的分層,更好的抽離業務邏輯關係,ABP是基於EF做數據訪問層,本人個人比較喜歡Dapper,就把數據訪問層封裝成了Dapper 使用技術包括:WebApi、OAuth2、Dapper、Log4Net、Swagger、Autof ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...