花鬼の庵

開発とかゲームとか実況とか

【C#】で行うDB接続とクエリ文の実行、値の受け取り

C#でDBへ接続して値を保存したり受け取ったり検証したり…。
プロジェクトの始めに用意するものの一つなので備忘録的に残して置こうかと思います。

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

namespace DBconnectTest
{
    class DBconnect
    {
        /// <summary>
        /// 接続情報
        /// </summary>
        static public string GetConnectionData()
        {
            return @"Data Source=localuser\test;"
                    + @"Integrated Security=false;"
                    + @"User ID=sa;"
                    + @"Password=123456"
                    + @"Initial Catalog=Test";
        }
        /// <summary>
        /// クエリ文を渡してDB処理開始
        /// </summary>
        static public SqlDataReader executeQueryToDataReader(SqlConnection connection, String sql, Dictionary<String, String> param = null)
        {
            SqlDataReader reader = null;

            try
            {
                // データベースの接続開始
                connection.Open();
                using (SqlCommand command = new SqlCommand() { CommandText = sql, Connection = connection })
                {
                    try
                    {
                        if (param != null)
                        {
                            foreach (string Key in param.Keys)
                            {
                                command.Parameters.AddWithValue(Key, param[Key]);
                            }
                        }

                        // SQLの実行
                        reader = command.ExecuteReader();
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                throw;
            }

            return reader;
        }
    }
}

簡単に解説

public string GetConnectionData 関数内の接続情報に関しては各々使用しているDBの情報へ下記直す必要がある。

Data Source=サーバー名
Integrated Security=Windowsアカウントの資格情報を使用するかどうか
User ID=ユーザーID
Password=パスワード
Initial Catalog=DB名

なお、今回は接続情報をべた書きしている。
個人開発でなら何も問題ないが、app.configから取得するようにした方がスマートなソースになる。
もし要望があればそちらの書き方も別途追記する…かもしれない。

public SqlDataReader executeQueryToDataReader 関数に関してはコピペで問題ない。
ただ、新規プロジェクトではSqlDataReaderを使う際、
パッケージSystem.Data.SqlClientのインストールが必要になる。
(インストールしていない場合下記画像のようにエラーがでる)
visual studio 2019を使用しているならSqlDataReaderを記載したあと、SqlDataReaderにカーソルを合わせて

"System.Data.SqlClient"のインストール→最新バージョンの検索とインストール→変更のプレビューをクリック→適用をクリック

することでSystem.Data.SqlClientがインストールされ、エラーが消える。

実装例

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

namespace CheckSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            // DB接続
            string connectionString = DBconnect.GetConnectionString();
            StringBuilder sql = new StringBuilder();

            // クエリ文実行
            sql.AppendLine("SELECT * FROM M_手順");
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataReader data = DBconnect.executeQueryToDataReader(connection, sql.ToString());

                if (data.HasRows)
                {
                    // 行数分ループ
                    while (data.Read())
                    {
                        // 列数分繰り返し
                        for (int i = 0; i < data.FieldCount; i++)
                        {
                            Console.Write(data[i] + ":");
                        }
                        Console.Write("\n");
                    }
                }
            }
        }
    }
}

実際に動作させます。

しっかりと指定したテーブルの内容が出力出来ました。

締め

DBの接続自体は簡単にできますが、問題はクエリ文ですよね…。 思うように出力した値が探しだせず悶々とする日々です。 joinとかは今でも正直ニュアンスで使っています。

なにか質問等々ございましたらコメントいただければと思います。

続き↓保存とか更新とか削除とか hanaonieruni.hatenablog.com