33
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データベース操作を管理するクラスを作成してみる(C#, SQLServer)

Last updated at Posted at 2018-05-27

データベース操作系の処理を一つのクラスにまとめてみます。
DB処理の基本的な内容となります。

#サンプルコード

##データベース操作を管理するクラス(DBManager.cs)

DBManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data;
using System.Data.SqlClient;

namespace ConsoleApp01
{
    /// <summary>
    /// データベース操作を管理するクラス
    /// </summary>
    class DBManager
    {
        private SqlConnection sqlConnection;
        private SqlTransaction sqlTransaction;

        /// <summary>
        /// コンストラクタ(DB接続)
        /// <para name="dbServer">DBサーバ名</para>
        /// <para name="dbName">DB名</para>
        /// <para name="dbUser">ユーザ名</para>
        /// <para name="dbPass">パスワード</para>
        /// </summary>
        public DBManager(string dbServer, string dbName, string dbUser, string dbPass)
        {
            // 接続文字列を生成
            string connectString =
            "Data Source = " + dbServer
            + ";Initial Catalog = " + dbName
            + ";User ID = " + dbUser
            + ";Password = " + dbPass
            + ";MultipleActiveResultSets=True";

            // SqlConnection の新しいインスタンスを生成 (接続文字列を指定)
            this.sqlConnection = new SqlConnection(connectString);

            // データベース接続を開く
            this.sqlConnection.Open();
        }

        /// <summary>
        /// DB切断
        /// </summary>
        public void Close()
        {
            this.sqlConnection.Close();
            this.sqlConnection.Dispose();
        }

        /// <summary>
        /// トランザクション開始
        /// </summary>
        public void BeginTran()
        {
            this.sqlTransaction = this.sqlConnection.BeginTransaction();
        }

        /// <summary>
        /// トランザクション コミット
        /// </summary>
        public void CommitTran()
        {
            if (this.sqlTransaction.Connection != null)
            {
                this.sqlTransaction.Commit();
                this.sqlTransaction.Dispose();
            }
        }

        /// <summary>
        /// トランザクション ロールバック
        /// </summary>
        public void RollBack()
        {
            if (this.sqlTransaction.Connection != null)
            {
                this.sqlTransaction.Rollback();
                this.sqlTransaction.Dispose();
            }
        }

        /// <summary>
        /// クエリー実行(OUTPUT項目あり)
        /// <para name="query">SQL文</para>
        /// <para name="paramDict">SQLパラメータ</para>
        /// </summary>
        public SqlDataReader ExecuteQuery(string query, Dictionary<string, Object> paramDict)
        {
            SqlCommand sqlCom = new SqlCommand();

            //クエリー送信先、トランザクションの指定
            sqlCom.Connection = this.sqlConnection;
            sqlCom.Transaction = this.sqlTransaction;

            sqlCom.CommandText = query;
            foreach (KeyValuePair<string, Object> item in paramDict)
            {
                sqlCom.Parameters.Add(new SqlParameter(item.Key, item.Value));
            }

            // SQLを実行
            SqlDataReader reader = sqlCom.ExecuteReader();

            return reader;
        }

        /// <summary>
        /// クエリー実行(OUTPUT項目あり)
        /// <para name="query">SQL文</para>
        /// </summary>
        public SqlDataReader ExecuteQuery(string query)
        {
            return this.ExecuteQuery(query, new Dictionary<string, Object>());
        }

        /// <summary>
        /// クエリー実行(OUTPUT項目なし)
        /// <para name="query">SQL文</para>
        /// <para name="paramDict">SQLパラメータ</para>
        /// </summary>
        public void ExecuteNonQuery(string query, Dictionary<string, Object> paramDict)
        {
            SqlCommand sqlCom = new SqlCommand();

            //クエリー送信先、トランザクションの指定
            sqlCom.Connection = this.sqlConnection;
            sqlCom.Transaction = this.sqlTransaction;

            sqlCom.CommandText = query;
            foreach(KeyValuePair<string, Object> item in paramDict) {
                sqlCom.Parameters.Add(new SqlParameter(item.Key, item.Value));
            }

            // SQLを実行
            sqlCom.ExecuteNonQuery();
        }
    }
}

##使用例(SELECT編)

sample1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data;
using System.Data.SqlClient;

namespace ConsoleApp01
{
    /// <summary>
    /// 使用例(SELECT編)
    /// </summary>
    class Program
    {
        //データベース接続情報
        private const string DATABASE_SERVER = "hogehoge";
        private const string DATABASE_NAME = "honyararaDB";
        private const string DATABASE_USER = "sa";
        private const string DATABASE_PASSWORD = "naishowords";

        /// <summary>
        /// Mainメソッド
        /// </summary>
        public static void Main(string[] args)
        {
            DBManager dbmanager = new DBManager(DATABASE_SERVER, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD);
            try
            {
                dbmanager.BeginTran();

                string selectSql = @"SELECT * FROM fugagugaTable ";
                SqlDataReader reader = dbmanager.ExecuteQuery(selectSql);
                int uId_Or = reader.GetOrdinal("uId");
                int uNm_Or = reader.GetOrdinal("uNm");

                while (reader.Read())
                {
                    Decimal uId = reader.GetDecimal(uId_Or);
                    string uNm = reader.GetString(uNm_Or);

                    Console.WriteLine("uId: {0}, uNm: {1}", uId, uNm);
                }
                dbmanager.CommitTran();
            }
            catch (SqlException sqle)
            {
                Console.WriteLine("Number: {0}, Message: {1}", sqle.Number, sqle.Message);
                dbmanager.RollBack();
            }
            finally
            {
                dbmanager.Close();
            }
        }
    }
}

##使用例(INSERT編(UPDATE/DELETEも同様))

sample2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data;
using System.Data.SqlClient;

namespace ConsoleApp01
{
    /// <summary>
    /// 使用例(INSERT編(UPDATE/DELETEも同様))
    /// </summary>
    class Program
    {
        //データベース接続情報
        private const string DATABASE_SERVER = "hogehoge";
        private const string DATABASE_NAME = "honyararaDB";
        private const string DATABASE_USER = "sa";
        private const string DATABASE_PASSWORD = "naishowords";

        /// <summary>
        /// Mainメソッド
        /// </summary>
        public static void Main(string[] args)
        {
            DBManager dbmanager = new DBManager(DATABASE_SERVER, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD);
            try
            {
                dbmanager.BeginTran();

                string insertSql = @"INSERT INTO fugagugaTable (COL_A, COL_B, COL_C) VALUES (@COL_A, @COL_B, @COL_C )";
                Dictionary<String, Object> paramDict = new Dictionary<string, Object>();
                paramDict.Add("@COL_A", "値あ");
                paramDict.Add("@COL_B", "値い");
                paramDict.Add("@COL_C", "値う");
                dbmanager.ExecuteNonQuery(insertSql, paramDict);

                dbmanager.CommitTran();
            }
            catch (SqlException sqle)
            {
                Console.WriteLine("Number: {0}, Message: {1}", sqle.Number, sqle.Message);
                dbmanager.RollBack();
            }
            finally
            {
                dbmanager.Close();
            }
        }
    }
}

以上です。

33
63
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?