すぐ使えるADO.NET

【Visual BasicによるADO.NETデータベースプログラミング】

本の紹介

バックナンバー:VB.NETデータベースプログラミング

ADO.NETの基本的なプログラミングを中心に、すぐ使えるサンプルプログラム満載です。




【第46号】

 第46号(2006.9.26発行)
======================================================================
           ★★ VB.NETデータベースプログラミング奮闘記 ★★
----------------------------------------------------------------------
いつもご購読ありがとうございます。ADO.NETの基本的なプログラミングを中
心に掲載しますので、今後ともよろしくお願い申し上げます。

すぐ使えるADO.NET --> サンプルプログラム満載
                      http://park5.wakwak.com/‾weblab/
======================================================================
             ■■ VB.NETワンポイント:Option Explicit On ■■

新規プロジェクトを作成すると、Option Explicit は既定値では Offに設定さ
れています。可能な限り Option Explicit を On に設定し直してください。
または、明示的に、Option Explicit On をソースファイルの先頭に記述する
こともできます。

データの欠落が起こる可能性のある変換をした場合、Object型のインスタンス
を使用して、実行時まで値が評価されない場合、宣言でAs句を省略した場合な
どは、Option Explicit On にすると、コンパイルエラーになります。実行時
エラーやバグを減らすためには、Option Explicit On でコーディングしたほう
が良いと考えています。

VB 2005 Express Edition では、Option Explicit は既定値で On になってい
ます。

----------------------------------------------------------------------
     ■■ データベースアクセスクラスの汎用メソッドについて 15 ■■

今号は、clsDBIOクラスの全ソースリストを掲載します。一部追加コーディン
グした部分がありますが、★を付加したコメントで明記してあります。コメン
ト部分も一部追加・修正してありますが、ソースの内容に変更はありません。

'----------------- << データベースアクセスクラス >> -----------------
Option Explicit On

Imports System.Data.OleDb
Imports System.Text.RegularExpressions

'--------------- << データベースアクセスクラス >> ---------------
Public Class clsDBIO

  '--------------------< メンバ:変数 >--------------------
  'コネクション
  Private mConn As OleDbConnection
  'コマンド
  Private mCommand As OleDbCommand
  'TABLE名コレクション
  Private mTableNameList As New Collection()

  '*******************************************************************
  ' 機能:コンストラクタ
  ' 引数:なし
  '*******************************************************************
  Public Sub New()

    Try
      'DB接続文字列の設定
      mConn = New OleDbConnection()
      mConn.ConnectionString = _
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" _
      & Application.StartupPath & "¥sample.mdb"

      'コネクションオブジェクトの設定
      mCommand = New OleDbCommand()
      mCommand.Connection = mConn

      '********** << テーブル名を取得 >> **********
      Dim schemaTable As DataTable

      mConn.Open()

      ' テーブル名を取得
      schemaTable = mConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, _
      New Object() {Nothing, Nothing, Nothing, "TABLE"})

      Dim i As Integer
      For i = 0 To schemaTable.Rows.Count - 1
        mTableNameList.Add(schemaTable.Rows(i)("TABLE_NAME").ToString)
      Next i

    Catch oExcept As OleDbException
      Throw New Exception _
      ("clsDBIOのコンストラクタで例外発生" + oExcept.ToString)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのコンストラクタで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

  End Sub

  '****************************************************************************
  ' 機能:キー値のレコードの有無を調べるメソッド
  ' 引数:テーブル名、キー値
  ' 戻値:ある-->True、ない-->False
  ' 備考:キー値は英数字 "_" "-" で構成されていること
  '****************************************************************************
  Public Function existKeyRecord( _
    ByVal parTableName As String, ByVal parKeyValue As String) As Boolean

    Dim retBool As Boolean                      'リターン値

    Try

      'テーブル名チェック
      Dim tblNames As String
      Dim existFlg As Boolean

      For Each tblNames In mTableNameList
        If tblNames = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblNames
      If Not existFlg = True Then
        Throw New myDBIOException("エラー:テーブル名不正")
      End If

      '前後の空白は除去する
      parKeyValue = parKeyValue.Trim()
      'キー値チェック(注:キー値は英数字と_と-で構成されている)
      If Not Regex.IsMatch(parKeyValue, "^[0-9a-zA-Z_¥-]+$") Then
        '英数字以外はエラー
        Throw New myDBIOException("エラー:キー値が正しくありません")
      End If

      'DB接続を開く
      mConn.Open()

      '主キーを取得
      Dim schemaTable As DataTable = _
      mConn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, _
      New Object() {Nothing, Nothing, parTableName})

      Dim keyField As String
      Dim wherePhrase As String
      Dim oleDbPara As String

      mCommand.Parameters.Clear()
      keyField = schemaTable.Rows(0).Item(3).ToString
      wherePhrase += " " + keyField + "= @key"

      '***** SQL文の引数設定 *****
      mCommand.Parameters.Clear()
      '入力引数の場合、Size指定は不要
      mCommand.Parameters.Add( _
      New OleDbParameter("@key", OleDbType.Char))

      '----------< コマンドパラメータに値を設定 >----------
      mCommand.Parameters("@key").Value = parKeyValue  'キー値の設定

      'SQL文設定
      mCommand.CommandText = _
      "SELECT COUNT(*) FROM " + parTableName + " WHERE" + wherePhrase

      'レコード件数取得
      Dim Count As Integer = CInt(mCommand.ExecuteScalar())

      '----------< 戻値を設定 >----------
      If Count = 1 Then
        retBool = True
      Else
        retBool = False
      End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのexistKeyRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retBool

  End Function

  '****************************************************************************
  ' 機能:複数キー値のレコードの有無を調べるメソッド
  ' 引数:テーブル名、キーフィールド名配列、キー値配列
  ' 戻値:ある-->True、ない-->False
  ' 備考:キー値は英数字 "_" "-" で構成されていること
  '****************************************************************************
  Public Function existKeyRecord(ByVal parTableName As String, _
                                 ByVal parKeyfield() As String, _
                                 ByVal parKeyValue() As String) As Boolean

    Dim keyList As New Collection()
    Dim retBool As Boolean                      'リターン値
    Dim i As Integer

    Try

      '引数未設定チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名が未設定")
      End If
      If parKeyfield Is Nothing Then
        Throw New myDBIOException("引数主キーフィールドが未設定")
      End If
      If parKeyValue Is Nothing Then
        Throw New myDBIOException("引数主キー値が未設定")
      End If

      'テーブル名チェック
      Dim tblName As String
      Dim existFlg As Boolean

      For Each tblName In mTableNameList
        If tblName = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblName

      If Not existFlg = True Then
        Throw New myDBIOException("テーブル名不正")
      End If

      'DB接続を開く
      mConn.Open()

      '主キーを取得
      Dim schemaTable As DataTable

      schemaTable = mConn.GetOleDbSchemaTable( _
                    OleDbSchemaGuid.Primary_Keys, _
                    New Object() {Nothing, Nothing, parTableName})

      '主キーフィールド数チェック
      If Not parKeyfield.Length = schemaTable.Rows.Count Then
        Throw New myDBIOException( _
        "引数の主キー数がテーブルの主キー数と不一致")
      End If

      '主キー値数チェック
      If Not parKeyValue.Length = schemaTable.Rows.Count Then
        Throw New myDBIOException( _
        "引数の主キー値数がテーブルの主キーフィールド数と不一致")
      End If

      For i = 0 To schemaTable.Rows.Count - 1
        keyList.Add(schemaTable.Rows(i).Item(3).ToString)
      Next i

      Dim wherePhrase As String
      Dim paraStr As String
      Dim keyName As String

      mCommand.Parameters.Clear()

      For i = 0 To schemaTable.Rows.Count - 1

        existFlg = False
        For Each keyName In keyList
          If keyName = parKeyfield(i) Then
            existFlg = True
            Exit For
          End If
        Next keyName

        If Not existFlg = True Then
          Throw New myDBIOException( _
          (i + 1).ToString + "番目のキーフィールド名不正")
        End If

        'キー値チェック(注:キー値は英数字と_と-で構成されている場合)
        parKeyValue(i) = parKeyValue(i).Trim()
        If Not Regex.IsMatch(parKeyValue(i), "^[0-9a-zA-Z_¥-]+$") Then
          'キー値は英数字 "_" "-"以外はエラー
          Throw New myDBIOException( _
          (i + 1).ToString + "番目のキー値が正しくありません")
        End If

        paraStr = "@key" + i.ToString
        wherePhrase += " " + parKeyfield(i) + "=" + paraStr
        'WHERE句をANDで区切る
        If Not i = schemaTable.Rows.Count - 1 Then
          wherePhrase += " AND "
        End If

        '***** SQL文の引数設定 *****
        mCommand.Parameters.Add( _
          New OleDbParameter(paraStr, OleDbType.Char))

        '----------< コマンドパラメータに値を設定 >----------
        mCommand.Parameters(paraStr).Value = parKeyValue(i)

      Next i

      'SQL文設定
      mCommand.CommandText = _
      "SELECT COUNT(*) FROM " + parTableName + " WHERE" + wherePhrase

      'レコード件数取得
      Dim Count As Integer = CInt(mCommand.ExecuteScalar())

      '----------< 戻値を設定 >----------
      If Count = 1 Then
        retBool = True
      Else
        retBool = False
      End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)
    Catch oExcept As Exception
      Throw New Exception _
      ("clsTableSyainのexistKeyRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retBool

  End Function

  '*******************************************************************
  ' 機能:引数にテーブルと主キー値を指定し、レコードを取得するメソッド
  ' 引数:String型:テーブル名
  ' 引数:String型:主キー値
  ' 戻値:DataTable型:取得したレコード
  ' 備考:キー値は英数字 "_" "-" で構成されていること
  '*******************************************************************
  Public Function getKeyRecord(ByVal parTableName As String, _
                               ByVal parKeyValue As String) As DataTable

    Dim retDataTable As New DataTable()                 'リターン値

    Try

      '引数Nothing(未設定)チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名が未設定")
      End If
      If parKeyValue Is Nothing Then
        Throw New myDBIOException("引数主キー値が未設定")
      End If

      'テーブル名チェック
      Dim tblNames As String
      Dim existFlg As Boolean

      For Each tblNames In mTableNameList
        If tblNames = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblNames
      If Not existFlg = True Then
        Throw New myDBIOException("エラー:テーブル名不正")
      End If

      '前後の空白は除去する
      parKeyValue = parKeyValue.Trim()
      'キー値チェック(注:キー値は英数字と_と-で構成されている)
      If Not Regex.IsMatch(parKeyValue, "^[0-9a-zA-Z_¥-]+$") Then
        'キー値は英数字 "_" "-"以外はエラー
        Throw New myDBIOException("エラー:キー値が正しくありません")
      End If

      'DB接続を開く
      mConn.Open()

      '主キーを取得
      Dim schemaTable As DataTable = _
      mConn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, _
      New Object() {Nothing, Nothing, parTableName})

      Dim keyField As String
      Dim wherePhrase As String
      Dim oleDbPara As String

      mCommand.Parameters.Clear()
      keyField = schemaTable.Rows(0).Item(3).ToString
      wherePhrase = keyField + "= @key"

      '***** SQL文の引数設定 *****
      mCommand.Parameters.Clear()
      '入力引数の場合、Size指定は不要
      mCommand.Parameters.Add( _
      New OleDbParameter("@key", OleDbType.Char))

      '----------< コマンドパラメータに値を設定 >----------
      mCommand.Parameters("@key").Value = parKeyValue  'キー値の設定

      'SQL文設定
      mCommand.CommandText = _
      "SELECT * FROM " + parTableName + " WHERE " + wherePhrase

      'テーブルからレコード取得
      Dim dataAdapter As New OleDbDataAdapter()

      dataAdapter.SelectCommand = mCommand
      dataAdapter.Fill(retDataTable)

    Catch oExcept As myDBIOException                    '★ 追加
      Throw New myDBIOException(oExcept.Message)
'★ 追加

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのgetKeyRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆戻値を設定してリターン
    Return retDataTable

  End Function

  '****************************************************************************
  ' 機能:複数キー値のレコードを取得するメソッド
  ' 引数:String型:テーブル名
  ' 引数:String型:主キーフィールド名配列
  ' 引数:String型:主キーフィールドに対応するキー値配列
  ' 戻値:DataTable型:取得したレコード
  ' 備考:キー値は英数字 "_" "-" で構成されていること
  '****************************************************************************
  Public Function getKeyRecord(ByVal parTableName As String, _
                               ByVal parKeyfields() As String, _
                               ByVal parKeyValues() As String) As DataTable

    Dim retDataTable As New DataTable()                 'リターン値
    Dim keyList As New Collection()
    Dim i As Integer

    Try

      '引数チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名が未設定")
      End If
      If parKeyfields Is Nothing Then
        Throw New myDBIOException("引数主キーフィールドが未設定")
      End If
      If parKeyValues Is Nothing Then
        Throw New myDBIOException("引数主キー値が未設定")
      End If

      'テーブル名チェック
      Dim tblName As String
      Dim existFlg As Boolean

      For Each tblName In mTableNameList
        If tblName = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblName

      If Not existFlg = True Then
        Throw New myDBIOException("テーブル名不正")
      End If

      'DB接続を開く
      mConn.Open()

      '主キーを取得
      Dim schemaTable As DataTable
      schemaTable = mConn.GetOleDbSchemaTable( _
                    OleDbSchemaGuid.Primary_Keys, _
                    New Object() {Nothing, Nothing, parTableName})

      '主キーフィールド数チェック
      If Not parKeyfields.Length = schemaTable.Rows.Count Then
        Throw New myDBIOException( _
        "引数の主キーフィールド数がテーブル主キーフィールド数と不一致")
      End If

      '主キー値数チェック
      If Not parKeyValues.Length = schemaTable.Rows.Count Then
        Throw New myDBIOException( _
        "引数の主キー値数がテーブルの主キーフィールド数と不一致")
      End If

      For i = 0 To schemaTable.Rows.Count - 1
        keyList.Add(schemaTable.Rows(i).Item(3).ToString)
      Next i

      Dim wherePhrase As String
      Dim paraStr As String
      Dim keyName As String

      mCommand.Parameters.Clear()

      For i = 0 To schemaTable.Rows.Count - 1

        existFlg = False
        For Each keyName In keyList
          If keyName = parKeyfields(i) Then
            existFlg = True
            Exit For
          End If
        Next keyName

        If Not existFlg = True Then
          Throw New myDBIOException( _
          (i + 1).ToString + "番目のキーフィールド名不正")
        End If

        'キー値チェック(注:キー値は英数字と_と-で構成されている場合)
        parKeyValues(i) = parKeyValues(i).Trim()
        If Not Regex.IsMatch(parKeyValues(i), "^[0-9a-zA-Z_¥-]+$") Then
          'キー値は英数字 "_" "-"以外はエラー
          Throw New myDBIOException( _
          "エラー:" + (i + 1).ToString + "番目のキー値が正しくありません")
        End If

        paraStr = "@key" + i.ToString
        wherePhrase += " " + parKeyfields(i) + "=" + paraStr
        'WHERE句をANDで区切る
        If Not i = schemaTable.Rows.Count - 1 Then
          wherePhrase += " AND "
        End If

        '***** SQL文の引数設定 *****
        mCommand.Parameters.Add( _
        New OleDbParameter(paraStr, OleDbType.Char))

        '----------< コマンドパラメータに値を設定 >----------
        mCommand.Parameters(paraStr).Value = parKeyValues(i)

      Next i

      'SQL文設定
      mCommand.CommandText = _
      "SELECT * FROM " + parTableName + " WHERE" + wherePhrase

      'テーブルからレコード取得
      Dim dataAdapter As New OleDbDataAdapter()

      dataAdapter.SelectCommand = mCommand
      dataAdapter.Fill(retDataTable)

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのgetKeyRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retDataTable

  End Function

  '****************************************************************************
  ' 機能:引数に指定した主キー値の範囲のレコードを取得するメソッド
  ' 引数:String型-->テーブル名
  ' 引数:String型-->主キーの最少値
  ' 引数:String型-->主キーの最大値
  ' 引数:String型-->主キーフィールド名(指定しない場合には、既定値の空文字列)
  ' 戻値:DataTable型:取得したレコード
  ' 備考:キー値は英数字 "_" "-" で構成されていること
  '****************************************************************************
  Public Function getRecordsOfRangeOfKey( _
                        ByVal parTableName As String, _
                        ByVal parMinValueOfKey As String, _
                        ByVal parMaxValueOfKey As String, _
                        Optional ByVal parKeyfield As String = "") _
                        As DataTable

    Dim retDataTable As New DataTable()                 'リターン値

    Try

      '引数チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名未設定")
      End If
      If parMinValueOfKey Is Nothing Then
        Throw New myDBIOException("引数主キー範囲最小値未設定")
      End If
      If parMaxValueOfKey Is Nothing Then
        Throw New myDBIOException("引数主キー範囲最大値未設定")
      End If
      If parMinValueOfKey > parMaxValueOfKey Then
        Throw New myDBIOException _
        ("エラー:引数主キー範囲最小値が最大値より大きくなっています")
      End If

     'テーブル名チェック
      Dim tblName As String
      Dim existFlg As Boolean

      For Each tblName In mTableNameList
        If tblName = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblName

      If Not existFlg = True Then
        Throw New myDBIOException("テーブル名不正")
      End If

      'DB接続を開く
      mConn.Open()

      '主キーフィールドの取得及びエラーチェック
      Dim schemaTable As DataTable
      schemaTable = mConn.GetOleDbSchemaTable( _
                    OleDbSchemaGuid.Primary_Keys, _
                    New Object() {Nothing, Nothing, parTableName})

      If parKeyfield = "" Then
        If schemaTable.Rows.Count = 1 Then
          parKeyfield = schemaTable.Rows(0).Item(3).ToString
        Else
          Throw New myDBIOException("引数主キーフィールド未設定")
        End If
      Else
        Dim keyList As New Collection()
        Dim i As Integer

        For i = 0 To schemaTable.Rows.Count - 1
          keyList.Add(schemaTable.Rows(i).Item(3).ToString)
        Next i

        Dim keyName As String

        existFlg = False
        For Each keyName In keyList
          If keyName = parKeyfield Then
            existFlg = True
            Exit For
          End If
        Next keyName

        If Not existFlg = True Then
          Throw New myDBIOException("引数のキーフィールド名不正")
        End If

      End If

      mCommand.Parameters.Clear()

      'キー値チェック(注:キー値は英数字と_と-で構成されている場合)
      parMinValueOfKey = parMinValueOfKey.Trim()
      'キー値は英数字 "_" "-"以外はエラー
      If Not Regex.IsMatch(parMinValueOfKey, "^[0-9a-zA-Z_¥-]+$") Then
        Throw New myDBIOException( _
              "エラー:引数キー範囲最小値が正しくありません")
      End If

      parMaxValueOfKey = parMaxValueOfKey.Trim()
      'キー値は英数字 "_" "-"以外はエラー
      If Not Regex.IsMatch(parMaxValueOfKey, "^[0-9a-zA-Z_¥-]+$") Then
        Throw New myDBIOException( _
              "エラー:引数キー範囲最大値が正しくありません")
      End If


      '***** SQL文の引数設定 *****
      mCommand.Parameters.Add( _
      New OleDbParameter("@key1", OleDbType.Char))
      mCommand.Parameters.Add( _
      New OleDbParameter("@key2", OleDbType.Char))

      '----------< コマンドパラメータに値を設定 >----------
      mCommand.Parameters("@key1").Value = parMinValueOfKey
      mCommand.Parameters("@key2").Value = parMaxValueOfKey

      'SQL文設定
      Dim wherePhrase As String
      wherePhrase = " " + parKeyfield + ">= @key1 AND"
      wherePhrase += " " + parKeyfield + "<= @key2"
      mCommand.CommandText = _
      "SELECT * FROM " + parTableName + " WHERE" + wherePhrase

      'テーブルからレコード取得
      Dim dataAdapter As New OleDbDataAdapter()

      dataAdapter.SelectCommand = mCommand
      dataAdapter.Fill(retDataTable)

      '★ 追加:引数キー値長のチェック
      If retDataTable.Rows.Count > 0 Then

        Dim keyItemLength As Integer
        keyItemLength = retDataTable.Rows(0)(parKeyfield).ToString.Length

        If Not parMinValueOfKey.Length = keyItemLength Then
          Throw New myDBIOException( _
          "エラー:引数キー最小値の文字数が正しくありません")
        End If

        If Not parMaxValueOfKey.Length = keyItemLength Then
          Throw New myDBIOException( _
          "エラー:引数キー最大値の文字数が正しくありません")
        End If

       End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)
    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのgetRecordsOfRangeOfKeyで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retDataTable

  End Function

  '****************************************************************************
  ' 機能:テーブルの全レコードを取得するメソッド
  ' 引数:String型:テーブル名
  ' 戻値:DataTable型:取得したレコード
  '****************************************************************************
  Public Function getAllRecords(ByVal parTableName As String) As DataTable

    Dim retDataTable As New DataTable()                 'リターン値
    Dim keyList As New Collection()
    Dim i As Integer

    Try

      '引数チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名が未設定")
      End If

      'テーブル名チェック
      Dim tblName As String
      Dim existFlg As Boolean

      For Each tblName In mTableNameList
        If tblName = parTableName Then
          existFlg = True
          Exit For
        End If
      Next tblName

      If Not existFlg = True Then
        Throw New myDBIOException("テーブル名不正")
      End If

      'DB接続を開く
      mConn.Open()

      mCommand.Parameters.Clear()

      'SQL文設定
      mCommand.CommandText = "SELECT * FROM " + parTableName

      'テーブルからレコード取得
      Dim dataAdapter As New OleDbDataAdapter()

      dataAdapter.SelectCommand = mCommand
      dataAdapter.Fill(retDataTable)

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのgetAllRecordsで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retDataTable

  End Function

  '****************************************************************************
  ' 機能:社員テーブルに1レコードを追加するメソッド
  ' 引数:clsInsertSyain型:追加する1レコード分のデータ
  ' 戻値:integer型:追加したレコード数
  '****************************************************************************
  Public Function insertRecord(ByVal parSyain As clsInsertSyain) As Integer

    Dim retInsertCount As Integer                'リターン値
    Dim keyList As New Collection()
    Dim i As Integer

    Try

      '引数チェック
      If parSyain Is Nothing Then
        Throw New myDBIOException("引数が未設定")
      End If

      '----------<< 1.社員テーブルに1レコードを追加 >>----------
      '***** SQL文の設定 *****
      mCommand.CommandText = _
      "INSERT INTO " & _
      "社員テーブル(社員コード, 社員氏名, 社員カナ, 更新日時) " & _
      "VALUES(@sCode, @sSimei, @sKana, @kosinDate)"

      '***** SQL文の引数設定 *****
      mCommand.Parameters.Clear()
      mCommand.Parameters.Add _
      (New OleDbParameter("@sCode", OleDbType.Char, 5))
      mCommand.Parameters.Add _
      (New OleDbParameter("@sSimei", OleDbType.Char, 20))
      mCommand.Parameters.Add _
      (New OleDbParameter("@sKana", OleDbType.Char, 40))
      mCommand.Parameters.Add _
      (New OleDbParameter("@kosinDate", OleDbType.Date))

      '***** 引数に値を設定 *****
      mCommand.Parameters("@sCode").Value = parSyain.pSyainCode
      mCommand.Parameters("@sSimei").Value = parSyain.pSyainSimei
      mCommand.Parameters("@sKana").Value = parSyain.pSyainKana
      mCommand.Parameters("@kosinDate").Value = Now()

      'DB接続を開く
      mConn.Open()

      '***** トランザクション開始 *****
      Dim oTrans As OleDbTransaction

      oTrans = mConn.BeginTransaction
      mCommand.Transaction = oTrans

      '***** データベースの更新を実行  *****
      retInsertCount = mCommand.ExecuteNonQuery()

      If retInsertCount = 1 Then
        '***** トランザクション完了 *****
        oTrans.Commit()
      Else
        '◆レコード追加に失敗したらロールバックして例外スロー
        oTrans.Rollback()
        Throw New myDBIOException _
        ("社員テーブル:レコード追加処理が失敗しました。")
      End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのinsertRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retInsertCount

  End Function


  '****************************************************************************
  ' 機能:社員テーブルの1レコードを更新するメソッド
  ' 引数:clsUpdateSyain型:更新する1レコード分のデータ
  ' 戻値:integer型:更新したレコード数
  '****************************************************************************
  Public Function updateRecord(ByVal parSyain As clsUpdateSyain) As Integer

    Dim retUpdateCount As Integer                'リターン値
    Dim keyList As New Collection()
    Dim i As Integer

    Try

      '引数チェック
      If parSyain Is Nothing Then
        Throw New myDBIOException("引数が未設定")
      End If

      '----------<< 1.社員テーブルの1レコードを更新 >>----------
      '***** SQL文の設定 *****
      mCommand.CommandText = _
      "UPDATE 社員テーブル " + _
      "SET 社員氏名=@sSimei, 社員カナ=@sKana, 更新日時=now() " + _
      "WHERE 社員コード=@sCode AND 更新日時=@updateDate"

      '***** SQL文の引数設定 *****
      mCommand.Parameters.Clear()
      mCommand.Parameters.Add _
      (New OleDbParameter("@sSimei", OleDbType.Char, 20))
      mCommand.Parameters.Add _
      (New OleDbParameter("@sKana", OleDbType.Char, 40))
      mCommand.Parameters.Add _
      (New OleDbParameter("@sCode", OleDbType.Char, 5))
      mCommand.Parameters.Add _
      (New OleDbParameter("@updateDate", OleDbType.Date))

      '***** 引数に値を設定 *****
      mCommand.Parameters("@sSimei").Value = parSyain.pSyainSimei
      mCommand.Parameters("@sKana").Value = parSyain.pSyainKana
      mCommand.Parameters("@sCode").Value = parSyain.pSyainCode
      mCommand.Parameters("@updateDate").Value = parSyain.pUpdateTime

      'DB接続を開く
      mConn.Open()

      '***** トランザクション開始 *****
      Dim oTrans As OleDbTransaction
      oTrans = mConn.BeginTransaction
      mCommand.Transaction = oTrans

      '***** データベースの更新を実行  *****
      retUpdateCount = mCommand.ExecuteNonQuery()

      If retUpdateCount = 1 Then
        '***** トランザクション完了 *****
        oTrans.Commit()
      Else
        '◆レコード更新に失敗したらロールバックして例外スロー
        oTrans.Rollback()
        Throw New myDBIOException _
        ("社員テーブル:レコード更新処理が失敗しました。")
      End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのupdateRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retUpdateCount

  End Function

  '****************************************************************************
  ' 機能:社員テーブルの1レコードを削除するメソッド
  ' 引数:clsUpdateSyain型:削除する1レコード分のデータ
  ' 戻値:integer型:削除したレコード数
  '****************************************************************************
  Public Function deleteRecord(ByVal parSyain As clsDeleteSyain) As Integer

    Dim retDeleteCount As Integer                'リターン値
    Dim keyList As New Collection()
    Dim i As Integer

    Try

      '引数チェック
      If parSyain Is Nothing Then
        Throw New myDBIOException("引数が未設定")
      End If

      '----------<< 1.社員テーブルの1レコードを削除 >>----------
      '***** SQL文の設定 *****
      mCommand.CommandText = _
      "DELETE FROM 社員テーブル " + _
      "WHERE 社員コード=@sCode AND 更新日時=@updateDate"

      '***** SQL文の引数設定 *****
      mCommand.Parameters.Clear()
      mCommand.Parameters.Add _
      (New OleDbParameter("@sCode", OleDbType.Char, 5))
      mCommand.Parameters.Add _
      (New OleDbParameter("@updateDate", OleDbType.Date))

      '***** 引数に値を設定 *****
      mCommand.Parameters("@sCode").Value = parSyain.pSyainCode
      mCommand.Parameters("@updateDate").Value = parSyain.pUpdateTime

      'DB接続を開く
      mConn.Open()

      '***** トランザクション開始 *****
      Dim oTrans As OleDbTransaction
      oTrans = mConn.BeginTransaction
      mCommand.Transaction = oTrans

      '***** データベースの削除を実行  *****
      retDeleteCount = mCommand.ExecuteNonQuery()

      If retDeleteCount = 1 Then
        '***** トランザクション完了 *****
        oTrans.Commit()
      Else
        '◆レコード削除に失敗したらロールバックして例外スロー
        oTrans.Rollback()
        Throw New myDBIOException _
        ("社員テーブル:レコード削除処理が失敗しました。")
      End If

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのdeleteRecordで例外発生" + oExcept.ToString)

    Finally
      'DB接続を閉じる
      If Not mConn Is Nothing Then
        If mConn.State = ConnectionState.Open Then
          mConn.Close()
        End If
      End If

    End Try

    '◆リターン
    Return retDeleteCount

  End Function

  '****************************************************************************
  ' 機能:テーブル対応の1行を生成するメソッド
  ' 引数:String型:テーブル名
  ' 戻値:DataRow型:生成した行
  '****************************************************************************
  Public Function createDataRow(ByVal parTableName As String) As DataRow

    Dim retDataRow As DataRow                 'リターン値

    Try

      '引数チェック
      If parTableName = Nothing Then
        Throw New myDBIOException("引数テーブル名が未設定")
      End If

      'テーブル存在チェック
      If Me.existTable(parTableName) = False Then
        Throw New myDBIOException("テーブルが存在しません")
      End If

      Dim dt As DataTable

      dt = Me.getKeyRecord(parTableName, "9")
      retDataRow = dt.NewRow

    Catch oExcept As myDBIOException
      Throw New myDBIOException(oExcept.Message)

    Catch oExcept As Exception
      Throw New Exception _
      ("clsDBIOのcreateDataRowで例外発生" + oExcept.ToString)

    End Try

    Return retDataRow

  End Function

  '*******************************************************************
  ' 機能:テーブル名をチェックするメソッド
  ' 引数:String型:テーブル名
  ' 戻値:Boolean型:引数のテーブル名が正しい時True、誤っている時False
  '*******************************************************************
  Private Function existTable(ByVal parTableName As String) As Boolean

    Dim retBool As Boolean                   'リターン値
    Dim tblName As String
    Dim existFlg As Boolean

    For Each tblName In mTableNameList
      If tblName = parTableName Then
        retBool = True
        Exit For
      End If
    Next tblName

    If Not retBool = True Then
      retBool = False
    End If

    Return retBool

  End Function

End Class

----------------------------------------------------------------------
              ■■ 次号予告 第47号(10月19日発行予定) ■■
1. VB.NETワンポイント
2. データベースアクセスクラスの汎用メソッドについて 16

======================================================================
VB.NET データベースプログラミング奮闘記
  発行者:ウェブ実験室(-----@-----)
          http://park5.wakwak.com/‾weblab/
----------------------------------------------------------------------
このメールマガジン(マガジンID: 0000128094)は、
インターネットの本屋さん『まぐまぐ』から配信されています。
  http://www.mag2.com/

【購読中止の方法】購読の中止は次のホームページからお願い致します。
  http://park5.wakwak.com/‾weblab/
  http://www.mag2.com/m/0000128094.htm
----------------------------------------------------------------------
このメールマガジン及び「すぐ使えるADO.NET」ホームページで公開している
ソースプログラム・データの利用により生じた損害等については、発行者は
一切責任を負いません。ソースプログラムの再利用は自由です。著作権は発行
者が所有します。
このメールマガジン及び「すぐ使えるADO.NET」ホームページに掲載されてい
る会社名・製品名等は、各社の登録商標または商標です。
======================================================================

Copyright© すぐ使えるADO.NET. All rights reserved.