5
2

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 3 years have passed since last update.

PowerShellでSqlServerの操作クラスを作成

Last updated at Posted at 2020-03-31

PowerShell勉強用。

#環境
Windows10 Home
PSVersion 5.1

#操作クラス

SqlManager.ps1
using namespace System.Data;
using namespace System.Data.SqlClient;

# =============================================================
# Class    : SqlManager
# -------------------------------------------------------------
# Sunmmary : SqlServerの管理クラス
# =============================================================
class SqlManager
{
    # -------------------------------
    # Member
    # -------------------------------
    [SqlConnection]  $clsSqlConnect;
    [SqlTransaction] $clsSqlTran;

    # =============================================================
    # constructor : SqlManager
    # -------------------------------------------------------------
    # Summary     : コンストラクタ
    # Param1      : サーバー
    # Param2      : データベース
    # Param3      : ユーザー
    # Param4      : パスワード
    # =============================================================
    SqlManager([string]$strServer, [string]$strDatabase, [string]$strUserId, [string]$strPassword)
    {
        # 接続文字列の設定
        [string]$strConnectionString = "Data Source=$strServer;Initial Catalog=$strDatabase;User ID=$strUserId;Password=$strPassword;MultipleActiveResultSets=True";

        # DB接続
        $this.clsSqlConnect = [SqlConnection]::New($strConnectionString);
        $this.clsSqlConnect.Open();
    }

    # =============================================================
    # Method   : BeginTran
    # -------------------------------------------------------------
    # Summary  : トランザクション
    # =============================================================
    BeginTran()
    {
        $this.clsSqlTran = $this.clsSqlConnect.BeginTransaction();
    }

    # =============================================================
    # Method   : Commit
    # -------------------------------------------------------------
    # Summary  : コミット
    # =============================================================
    Commit()
    {
        if ($this.clsSqlTran.Connection -ne $null)
        {
            $this.clsSqlTran.Commit();
            $this.clsSqlTran.Dispose();
            $this.clsSqlTran = $null;
        }
    }

    # =============================================================
    # Method   : RollBack
    # -------------------------------------------------------------
    # Summary  : ロールバック
    # =============================================================
    RollBack()
    {
        if ($this.clsSqlTran.Connection -ne $null)
        {
            $this.clsSqlTran.Rollback();
            $this.clsSqlTran.Dispose();
            $this.clsSqlTran = $null;
        }
    }

    # =============================================================
    # Method   : Dispose
    # -------------------------------------------------------------
    # Summary  : 解放処理
    # =============================================================
    Dispose()
    {
        if ($this.clsSqlTran -ne $null)
        {
            $this.clsSqlTran.Dispose();
            $this.clsSqlTran = $null;
        }
        if ($this.clsSqlConnect -ne $null)
        {
            $this.clsSqlConnect.Dispose();
            $this.clsSqlConnect = $null;
        }
    }
    
    # =============================================================
    # Method   : Fill
    # -------------------------------------------------------------
    # Summary  : クエリの実行結果をデータテーブルで返す
    # Param1   : サーバー
    # Return   : 実行結果
    # =============================================================
    [DataTableCollection] Fill([string]$strQuery)
    {
        [SqlCommand]          $clsSqlCmd  = $null;
        [SqlDataAdapter]      $clsAdapter = $null;
        [DataSet]             $clsDataSet = $null;

        try
        {
            $clsSqlCmd             = $this.clsSqlConnect.CreateCommand();
            $clsSqlCmd.Connection  = $this.clsSqlConnect;
            $clsSqlCmd.Transaction = $this.clsSqlTran;
            $clsSqlCmd.CommandText = $strQuery;
            $clsAdapter            = [SqlDataAdapter]::New($clsSqlCmd);
            $clsDataSet            = [DataSet]::New();

            $clsAdapter.Fill($clsDataSet)   
        }
        finally
        {
            if($clsSqlCmd -ne $null)
            {
                $clsSqlCmd.Dispose();
                $clsSqlCmd = $null;
            }
            if($clsAdapter -ne $null)
            {
                $clsAdapter.Dispose();
                $clsAdapter = $null;
            }
        }
        return $clsDataSet.Tables;
    }

    # =============================================================
    # Method   : ExecuteQuery
    # -------------------------------------------------------------
    # Summary  : クエリの実行し、結果を返す
    # Param1   : 適用するクエリ
    # Return   : 実行結果
    # =============================================================
    [Boolean]ExecuteQuery([string]$strQuery)
    {
        [Boolean]        $bResult    = $false;
        [SqlCommand]     $clsSqlCmd  = $null;
        [SqlDataAdapter] $clsAdapter = $null;
        [DataSet]        $clsDataSet = $null;

        try
        {
            $clsSqlCmd             = $this.clsSqlConnect.CreateCommand();
            $clsSqlCmd.Connection  = $this.clsSqlConnect;
            $clsSqlCmd.Transaction = $this.clsSqlTran;
            $clsSqlCmd.CommandText = $strQuery;

            $clsSqlCmd.ExecuteNonQuery();
            $bResult = $true;
        }
        finally
        {
            if($clsSqlCmd -ne $null)
            {
                $clsSqlCmd.Dispose();
                $clsSqlCmd = $null;
            }
            if($clsAdapter -ne $null)
            {
                $clsAdapter.Dispose();
                $clsAdapter = $null;
            }
            if($clsDataSet -ne $null)
            {
                $clsDataSet.Dispose();
                $clsDataSet = $null;
            }
        }
        return $bResult;
    }
}

#使用方法

SqlMngTest.ps1
# -------------------------------
# 初期処理
# -------------------------------

# クラスの読み込み
# ⇒ 同一ディレクトリに存在する、SqlManager.ps1を実行させる
. (Join-Path $MyInvocation.MyCommand.Path ../SqlManager.ps1);

# SqlServer接続用の情報を設定
[string]$strServer   = 'localhost';
[string]$strDatabase = 'TempDB';
[string]$strUserId   = 'sa';
[string]$strPassword = 'sa';

# -------------------------------
# INSERT
# -------------------------------
try
{
    $clsSqlMng = [SqlManager]::New($strServer,$strDatabase,$strUserId,$strPassword);

    $clsSqlMng.BeginTran();

    [string] $strInsert = "insert into Hoge values ('000','TEST', 999)";
    
    $clsSqlMng.ExecuteQuery($strInsert);

    $clsSqlMng.Commit();
}
catch
{
    $clsSqlMng.RollBack();
}
finally
{
    $clsSqlMng.Dispose();
}

# -------------------------------
# SELECT
# -------------------------------
try
{
    $clsSqlMng = [SqlManager]::New($strServer,$strDatabase,$strUserId,$strPassword);

    [String]$strSelect = "SELECT * FROM Hoge";
    [Int32]$iCount = 1;
    
    foreach($item in $clsSqlMng.Fill($strSelect))
    {
        # 画面表示
        $item | format-table;

        # CSV保存
        $item | export-csv ("Result" + $iCount + ".csv") -Encoding default -NoTypeInformation;
        
        $iCount++;
    }
}
finally
{
    $clsSqlMng.Dispose();
}
5
2
0

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?