LoginSignup
2
4

More than 5 years have passed since last update.

C#のメモ帳 DBへ書き込む部分の関数化

Last updated at Posted at 2017-08-30

SQLのInput/Update/Deleteを関数にしクラスファイルにまとめた。

Input/Update/Deleteを実行

using System.Data;
using System.Data.SqlClient;    //DB接続用

namespace AAA
{
    class SQL実行系
    {

        // メソッドの定義 ここから----------------------------↓

        public string 実行(string DB接続文字列, string sql)
        {
            //引数は、DB接続文字列とSQL(Input/Update/Delete文)。
            //Insert, Update, Delete を実行した後、
            //OK/NGを戻す。


            string Result;

            using (SqlCommand command = new SqlCommand())
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = DB接続文字列;

                // トランザクションを開始します。
                conn.Open();
                SqlTransaction transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted);

                try
                {
                    command.CommandText = sql;
                    command.Connection = conn;
                    command.Transaction = transaction;
                    command.ExecuteNonQuery();

                    //トランザクションをコミットします。
                    transaction.Commit();
                    Result = "OK";
                }
                catch (System.Exception)
                {
                    //トランザクションをロールバックします。
                    transaction.Rollback();
                    Result = "NG";
                    return Result;
                }
                return Result;
            }  // このブロックを抜けたらcommand 、conn はDisposeされます。
        }

        // メソッドの定義 ここまで---------------------------------↑

    }
}
2
4
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
2
4