[C#]MS-SQL資料庫存取函式

序言

我將C#存取MS-SQL的程式包了一層方便使用。

環境

  • VS2008
  • MS-SQL 2008

存取函式類別

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Data;

namespace MyCommon.DAO
{

    /// 
    /// MS-SQL連線物件
    /// 
    public class MSSQLBaseIO
    {
        SqlConnection sqlConn = null;
        /// 
        /// 建立連線物件
        /// 
        /// 連線字串,如Data Source=localhost;Initial Catalog=dbName;User id=Account;Password=Password;
        public MSSQLBaseIO(string connectionString)
        {
            sqlConn = new SqlConnection(connectionString);
        }
        /// 
        /// 建立連線物件
        /// 
        /// 可為localhost / domainname  / 或 IP
        /// 若Host為IP,則需為true
        /// 不設定則填0,則會用MSSQL預設port
        /// 不設定則填null,express版預設為SQLEXPRESS,正式版預設為MSSQLSERVER,從服務組態可以看到
        /// 資料庫名稱
        /// 是否使用 Windows 整合驗証方式連線,false則必需填帳號密碼
        /// 登入帳號
        /// 登入密碼
        /// 連線逾期,不設定則填0
        public MSSQLBaseIO(string host,bool isHostIP,int port,
            string instanceName, string dbName,
            bool isIntegratedSecurity,
            string id, string password,
            int timeout)
        {
            StringBuilder connectionString = new StringBuilder();
            if (isHostIP) connectionString.Append("Data Source=tcp:" + host);
            else connectionString.Append("Data Source=" + host);
            if (instanceName != null) connectionString.Append("\\" + instanceName);
            if (port != 0) connectionString.Append("," + port);
            connectionString.Append(";");
            connectionString.Append("Initial Catalog=" + dbName + ";");
            if (isIntegratedSecurity) connectionString.Append("integrated security=true;");
            if (id!=null) connectionString.Append("User id=" + id + ";");
            if (password!=null) connectionString.Append("Password=" + password + ";");
            if (timeout>0) connectionString.Append("Connect Timeout=" + timeout + ";");
            sqlConn = new SqlConnection(connectionString.ToString());
        }
        /// 
        /// 取得目前連線物件
        /// 
        /// 
        public SqlConnection getConnection()
        {
            return sqlConn;
        }

        Exception _exception = null;
        /// 
        /// 取得上次執行後的錯誤
        /// 
        /// 
        public Exception getException(){
            return _exception;
        }
        /// 
        /// 關閉連線
        /// 
        public void closeConn()
        {
            closeConn(true);
        }
        /// 
        /// 關閉連線
        /// 
        /// 是否關閉連線
        public void closeConn(bool isCloseConn){
            if (sqlConn != null && isCloseConn && sqlConn.State!=System.Data.ConnectionState.Closed)
            {
                sqlConn.Close();
            }
        }
        /// 
        /// 取得新的Transaction物件
        /// 
        /// Transaction物件
        public SqlTransaction getNewTransaction()
        {
            if (sqlConn.State != System.Data.ConnectionState.Open)
                sqlConn.Open();
            return sqlConn.BeginTransaction();
        }

        /// 
        /// 執行SQL命令,執行後會關閉SQL連線
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 變動筆數
        public int ExecuteNonQuery(string sqlcmd, bool isStoredProcedure)
        {
            return ExecuteNonQuery(sqlcmd,isStoredProcedure, true);
        }
        /// 
        /// 執行SQL命令
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 是否關閉連線
        /// 變動筆數
        public int ExecuteNonQuery(string sqlcmd, bool isStoredProcedure, bool isCloseConn)
        {
            SqlParameter[] sqlparams = null;
            return ExecuteNonQuery(sqlcmd, ref sqlparams, isStoredProcedure, isCloseConn);
        }
        /// 
        /// 執行SQL命令
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// 是否關閉連線
        /// 變動筆數
        public int ExecuteNonQuery(string sqlcmd, ref SqlParameter[] sqlparams, bool isStoredProcedure, bool isCloseConn)
        {
            return ExecuteNonQuery(sqlcmd, ref sqlparams, isStoredProcedure, null, isCloseConn);
        }
        /// 
        /// 執行SQL命令
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// SqlTransaction,可為null
        /// 是否關閉連線
        /// 變動筆數
        public int ExecuteNonQuery(string sqlcmd, ref SqlParameter[] sqlparams,bool isStoredProcedure, SqlTransaction trans, bool isCloseConn)
        {
            int result = -1;
            _exception = null;
            try
            {
                if (sqlConn.State != System.Data.ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand cmd;
                if (trans==null)
                    cmd = new SqlCommand(sqlcmd, sqlConn);
                else
                    cmd = new SqlCommand(sqlcmd, sqlConn, trans);
                if(isStoredProcedure)
                    cmd.CommandType = CommandType.StoredProcedure;
                if (sqlparams!=null)
                    cmd.Parameters.AddRange(sqlparams);
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
            finally
            {
                closeConn(isCloseConn);
            }
            return result;
        }
        /// 
        /// 取得多列資料,執行後會關閉SQL連線
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 是否關閉連線
        /// 多列資料
        public List ExecuteReader(string sqlcmd, bool isStoredProcedure)
        {
            return ExecuteReader(sqlcmd, isStoredProcedure, true);
        }
        /// 
        /// 取得多列資料
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 是否關閉連線
        /// 多列資料
        public List ExecuteReader(string sqlcmd, bool isStoredProcedure, bool isCloseConn)
        {
            SqlParameter[] sqlparams = null;
            return ExecuteReader(sqlcmd, ref sqlparams, isStoredProcedure, isCloseConn);
        }
        /// 
        /// 取得多列資料
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// 是否關閉連線
        /// 多列資料
        public List ExecuteReader(string sqlcmd, ref SqlParameter[] sqlparams, bool isStoredProcedure, bool isCloseConn)
        {
            return ExecuteReader(sqlcmd, ref sqlparams, isStoredProcedure, null, isCloseConn);
        }
        /// 
        /// 取得多列資料
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// SqlTransaction,可為null
        /// 是否關閉連線
        /// 多列資料
        public List ExecuteReader(string sqlcmd, ref SqlParameter[] sqlparams, bool isStoredProcedure, SqlTransaction trans, bool isCloseConn)
        {
            List result = null;
            _exception = null;
            SqlDataReader reader = null;
            try
            {
                if (sqlConn.State != System.Data.ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand cmd;
                if (trans == null)
                    cmd = new SqlCommand(sqlcmd, sqlConn);
                else
                    cmd = new SqlCommand(sqlcmd, sqlConn, trans);
                if (isStoredProcedure)
                    cmd.CommandType = CommandType.StoredProcedure;
                if (sqlparams != null)
                    cmd.Parameters.AddRange(sqlparams);
                reader = cmd.ExecuteReader();
                object[] item;
                if (reader.HasRows)
                {
                    result = new List();
                    while (reader.Read())
                    {
                        item = new object[reader.FieldCount];
                        for (int j = 0; j < reader.FieldCount; j++)
                        {
                            item[j] = reader[j];
                        }
                        result.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
            finally
            {
                if (reader!=null) reader.Close();
                closeConn(isCloseConn);
            }
            return result;
        }

        /// 
        /// 取得單一值,執行後會關閉SQL連線
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 單一值
        public object ExecuteScalar(string sqlcmd, bool isStoredProcedure)
        {
            return ExecuteScalar(sqlcmd, isStoredProcedure, true);
        }
        /// 
        /// 取得單一值
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 是否關閉連線
        /// 單一值
        public object ExecuteScalar(string sqlcmd, bool isStoredProcedure, bool isCloseConn)
        {
            SqlParameter[] sqlparams = null;
            return ExecuteScalar(sqlcmd, ref sqlparams, isStoredProcedure, isCloseConn);
        }
        /// 
        /// 取得單一值
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// 是否關閉連線
        /// 單一值
        public object ExecuteScalar(string sqlcmd,ref SqlParameter[] sqlparams, bool isStoredProcedure, bool isCloseConn)
        {
            return ExecuteScalar(sqlcmd,ref sqlparams, isStoredProcedure, null, isCloseConn);
        }
        /// 
        /// 取得單一值
        /// 
        /// SQL命令
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// SqlTransaction,可為null
        /// 是否關閉連線
        /// 單一值
        public object ExecuteScalar(string sqlcmd,ref SqlParameter[] sqlparams, bool isStoredProcedure, SqlTransaction trans, bool isCloseConn)
        {
            object result = null;
            _exception = null;
            try
            {
                if (sqlConn.State != System.Data.ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand cmd;
                if (trans == null)
                    cmd = new SqlCommand(sqlcmd, sqlConn);
                else
                    cmd = new SqlCommand(sqlcmd, sqlConn, trans);
                if (isStoredProcedure)
                    cmd.CommandType = CommandType.StoredProcedure;
                if (sqlparams != null)
                    cmd.Parameters.AddRange(sqlparams);
                result = cmd.ExecuteScalar();
              
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
            finally
            {
                closeConn(isCloseConn);
            }
            return result;
        }

        /// 
        /// 取得單一列資料,執行後會關閉SQL連線
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 單一列資料
        public object[] ExecuteReaderSingleRow(string sqlcmd, bool isStoredProcedure)
        {
            return ExecuteReaderSingleRow(sqlcmd, isStoredProcedure, true);
        }
        /// 
        /// 取得單一列資料
        /// 
        /// SQL命令
        /// 是否為預存程序
        /// 是否關閉連線
        /// 單一列資料
        public object[] ExecuteReaderSingleRow(string sqlcmd, bool isStoredProcedure, bool isCloseConn)
        {
            SqlParameter[] sqlparams = null;
            return ExecuteReaderSingleRow(sqlcmd, ref sqlparams, isStoredProcedure, isCloseConn);
        }
        /// 
        /// 取得單一列資料
        /// 
        /// SQL命令,參數部份以 @參數名稱 標示
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// 是否關閉連線
        /// 單一列資料
        public object[] ExecuteReaderSingleRow(string sqlcmd,ref SqlParameter[] sqlparams, bool isStoredProcedure, bool isCloseConn)
        {
            return ExecuteReaderSingleRow(sqlcmd,ref sqlparams, isStoredProcedure, null, isCloseConn);
        }
        /// 
        /// 取得單一列資料
        /// 
        /// SQL命令,參數部份以 @參數名稱 標示
        /// 命令參數,可為null,參數名稱為 @參數名稱
        /// 是否為預存程序
        /// SqlTransaction,可為null
        /// 是否關閉連線
        /// 單一列資料
        public object[] ExecuteReaderSingleRow(string sqlcmd, ref SqlParameter[] sqlparams, bool isStoredProcedure, SqlTransaction trans, bool isCloseConn)
        {
            object[] result = null;
            _exception = null;
            SqlDataReader reader = null;
            try
            {
                if (sqlConn.State != System.Data.ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand cmd;
                if (trans == null)
                    cmd = new SqlCommand(sqlcmd, sqlConn);
                else
                    cmd = new SqlCommand(sqlcmd, sqlConn, trans);
                if (isStoredProcedure)
                    cmd.CommandType = CommandType.StoredProcedure;
                if (sqlparams != null)
                    cmd.Parameters.AddRange(sqlparams);
                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                object[] item;
                if (reader.HasRows)
                {
                    reader.Read();
                    item = new object[reader.FieldCount];
                    for (int j = 0; j < reader.FieldCount; j++)
                    {
                        item[j] = reader[j];
                    }
                    result = item;
                }
            }
            catch (Exception ex)
            {
                _exception = ex;
            }
            finally
            {
                if (reader != null) reader.Close();
                closeConn(isCloseConn);
            }
            return result;
        }
    }
}
 

0 意見:

這裡是關於技術的手札~

也歡迎大家到

倫與貓的足跡



到噗浪來

關心一下我唷!
by 倫
 
Copyright 2009 倫倫3號Beta-Log All rights reserved.
Blogger Templates created by Deluxe Templates
Wordpress Theme by EZwpthemes