1. 程式人生 > >C# sqlhelper 自練習

C# sqlhelper 自練習

tran strac erp rain 調用 span close mes 它的

以下代碼是參考幾個不同人的寫法總結寫成的,肯定還有很大的優化空間,暫存該版本;有建議的歡迎提出;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstBI
{
    public abstract class SqlHelpertrain//
定義為abstract抽象類,不能被實例化,在應用時直接調用 { /*1.獲取數據庫連接字符串; * 2.Connection 鏈接綁定,open/close; * 3.實例化一個Command命令,給定命令執行的超時時間 ,命令執行的連接;命令的類型(增/刪/改/查) * ,是否帶事務,執行用到哪些參數,還有最重要的命令執行的sql字符串; * 4.SqlDataAdapter承接命令返回的結果集 */ private static int TimeOut = 5000;
private static string connStrs = ConfigurationManager.ConnectionStrings["FirstBI.Properties.Settings.BaseERPConnectionString"].ConnectionString; /// <summary> /// 獲取SqlCommand /// </summary> /// <param name="conn"></param> /// <param name="cmdType"></param>
/// <param name="tran"></param> /// <param name="sqlParams"></param> /// <returns></returns> public static SqlCommand GetSqlCommand(string sql, SqlConnection conn, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandTimeout = TimeOut; cmd.CommandType = cmdType; if (tran != null) cmd.Transaction = tran; if (sqlParams != null && sqlParams.Length > 0) cmd.Parameters.AddRange(sqlParams); return cmd; } /// <summary> /// /// </summary> /// <param name="sql"></param> /// <param name="cmdType"></param> /// <param name="tran"></param> /// <param name="sqlParams"></param> /// <returns></returns> public static DataTable GetDataTable(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { using (SqlConnection conn = new SqlConnection(connStrs)) { try { conn.Open(); using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams)) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } catch (SqlException ex) { StringBuilder log = new StringBuilder(); log.Append("查詢數據錯誤:"); log.Append(ex); throw new Exception(log.ToString()); } finally { conn.Close(); } } } /// <summary> /// /// </summary> /// <param name="sql"></param> /// <param name="cmdType"></param> /// <param name="tran"></param> /// <param name="sqlParams"></param> /// <returns></returns> public static DataSet GetDataSet(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { using (SqlConnection conn = new SqlConnection(connStrs)) { using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams)) { try { conn.Open(); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); da.Fill(ds); return ds; } } catch (SqlException ex) { StringBuilder log = new StringBuilder(); log.Append("查詢數據錯誤:"); log.Append(ex); throw new Exception(log.ToString()); } finally { conn.Close(); } } } } /// <summary> /// /// </summary> /// <param name="sql"></param> /// <param name="cmdType"></param> /// <param name="tran"></param> /// <param name="sqlParams"></param> /// <returns></returns> public static int ExecNonQuery(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { /*定義: SqlCommand cmd = new SqlCommand();//或者SqlCommand cmd = new SqlConnection().CreateCommand(); 註意參數 cmd.CommandType = CommandType.StoredProcedure; //存儲過程 cmd.CommandType = CommandType.Text; //sql語句 cmd.CommandType = CommandType.TableDirect; System.Data.CommandType.TableDirect表示要執行的是表 ,此時,cmd.CommandText 的值應該是要查詢表的的名稱。查詢結果返回的是整個表。 */ int count = 0; using (SqlConnection conn = new SqlConnection(connStrs)) { using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams)) { try { conn.Open(); if (cmdType == CommandType.StoredProcedure) cmd.Parameters.AddWithValue("@RETURN_VALUE", "").Direction = ParameterDirection.ReturnValue; count = cmd.ExecuteNonQuery(); if (count <= 0) if (cmdType == CommandType.StoredProcedure) count = (int)cmd.Parameters["@RETURN_VALUE"].Value; } catch (SqlException ex) { StringBuilder log = new StringBuilder(); log.Append("查詢數據錯誤:"); log.Append(ex); throw new Exception(log.ToString()); } finally { conn.Close(); } } } return count; } public static object QueryScalar(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { using (SqlConnection conn = new SqlConnection(connStrs)) { using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams)) { try { conn.Open();//創建cmd之前或之後Open都是可以的 return cmd.ExecuteScalar(); } catch (SqlException ex) { StringBuilder log = new StringBuilder(); log.Append("查詢數據出錯:"); log.Append(ex); throw new Exception(log.ToString()); } finally { conn.Close(); } } } } /// <summary> /// /// </summary> /// <param name="sql"></param> /// <param name="cmdType"></param> /// <param name="tran"></param> /// <param name="sqlParams"></param> /// <returns></returns> public static SqlDataReader GetDataReader(string sql, CommandType cmdType, SqlTransaction tran, params SqlParameter[] sqlParams) { //SqlDataReader要求,它讀取數據的時候有,它獨占它的SqlConnection對象,而且SqlConnection必須是Open狀態 //SqlDataReader與SqlDataAdapter的區別:SqlDataReader為在線操作數據庫,SqlDataAdapter為離線操作(打開連接獲取數據集之後關閉連接,然後離線操作數據庫,然後再打開連接將數據更新到數據庫) using (SqlConnection conn = new SqlConnection(connStrs)) { using (SqlCommand cmd = GetSqlCommand(sql, conn, cmdType, tran, sqlParams)) { try { conn.Open(); //CommandBehavior.CloseConnection當SqlDataReader釋放的時候,順便把SqlConnection對象也釋放掉 return cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (SqlException ex) { StringBuilder log = new StringBuilder(); log.Append("查詢數據錯誤:"); log.Append(ex); throw new Exception(log.ToString()); } } } } } }

C# sqlhelper 自練習