忍者ブログ

VB.NET-TIPS などプログラミングについて

VB.NETのTIPS(小技集)を中心に、Javascript、PHP その他のプログラミングについて少し役に立つ情報を発信します。いわゆる個人的な忘備録ですが、みなさんのお役に立てれば幸いです。

VB.NET:ADO.NET を使用した SQL-Server へのアクセス・クラス
ADO.NET を使用した SQL-Server へのアクセス・クラスの簡単なものを作成してみました。
このクラスを元にして拡張したものを仕事でも使っています。

このクラス「clsSqlServer」には以下のメソッド・プロパティが備わっています。
メソッド・プロパティ概要
New コンストラクタ(引数にデータベース接続文字列を渡す)
BeginTransaction トランザクション開始
Commit トランザクションコミット
Rollback トランザクションロールバック
CloseConnection コネクションの解除
OpenDataReader SELECT文SQLの実行とDataReaderへの読込
CloseDataReader DataReaderのクローズ
ExeSQL DML-SQL文の実行
CnvReaderToHashtable DataReaderの結果ItemsをHashtableに変換


今回のクラスのテストプログラムを以下に載せますが、SQLサーバへの接続文字列は以下の様にしています。
キーワード概要(設定値)
Persist Security Info ID やパスワードなどのセキュリティ関連情報の破棄指定(False)
Integrated Security 現在のWindowsアカウントでの認証(SSPI)
Database データベース名(取敢えず「TEST」)
Data Source SQL Serverのインスタンスの名前
(Microsoft SQL Server Management Studio Express:.\SQLEXPRESS)


このテストは、システム日付をSELECTで実行し、SqlDataReaderに取得しています。SqlDataReaderから日付を取り出して その後、クラスのクローズを行っています。

■「clsSqlServer」の使用テストソース1
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    'SQL-Server接続クラス生成
    Dim DBConnection As String = "Persist Security Info=false;" & _
        "Integrated Security=SSPI;Database=TEST;Data Source=.\SQLEXPRESS;"
    Dim CSQL = New clsSqlServer(DBConnection)
    'TESTデータ取得クラス生成
    Dim SQL As String = "SELECT GETDATE() AS SYSDATE"
    Dim Reader As System.Data.SqlClient.SqlDataReader = Nothing
    If CSQL.OpenDataReader(SQL, Reader) = True Then
        '読込
        While Reader.Read() = True
            '読込が行われた場合,データをHashtableに格納
            Dim ht As Hashtable = CSQL.CnvReaderToHashtable(Reader)
            MsgBox(ht("SYSDATE") & " : " & Reader.Item("SYSDATE"))
        End While
    End If
    'クローズ
    CSQL.CloseConnection()
End Sub


以下に、clsSqlServerの全体のソースを載せます。バグがあるかもしれませんが悪しからず。

■「clsSqlServer」のソース
Imports System.Data.SqlClient
''' ======================================================================
''' 
''' SQLServer処理用クラス
''' 
''' ======================================================================
Class clsSqlServer
    'コネクションを共有変数で持つ
    Private _Conn As SqlConnection = Nothing
    'トランザクションを共有変数で持つ
    Private _Trans As SqlTransaction = Nothing
    '接続文字列
    Private _DBConnection As String
    '最後の実行SQL文および、エラーメッセージ
    Private _LastSQL As String = ""
    Private _LastErr As String = ""

    ' --------------------------------------------------------------------
    ' プロパティ
    ' --------------------------------------------------------------------

    ''' -------------------------------------------------------------------
    ''' 最終実行SQL文
    ''' -------------------------------------------------------------------
    Public ReadOnly Property LastSQL() As String
        Get
            Return Me._LastSQL
        End Get
    End Property
    ''' -------------------------------------------------------------------
    ''' 最終エラーメッセージ
    ''' -------------------------------------------------------------------
    Public ReadOnly Property LastErr() As String
        Get
            Return Me._LastErr
        End Get
    End Property

    ''' -------------------------------------------------------------------
    ''' コンストラクタ
    '''データベース接続文字列
    ''' -------------------------------------------------------------------
    Public Sub New(ByVal DBConnection As String)
        'データベース接続文字列の退避
        Me._DBConnection = DBConnection
    End Sub

    ''' -------------------------------------------------------------------
    ''' 
    ''' トランザクション開始
    ''' 
    ''' 処理結果(true:OK, false:NG)
    ''' -------------------------------------------------------------------
    Public Function BeginTransaction() As Boolean
        Try
            _Trans = _Conn.BeginTransaction(IsolationLevel.ReadCommitted)
            Return True
        Catch ex As Exception
            Me._LastErr = ex.ToString()
            _Trans = Nothing
            Return False
        End Try
    End Function

    ''' -------------------------------------------------------------------
    ''' 
    ''' トランザクションコミット
    ''' 
    ''' -------------------------------------------------------------------
    Public Sub Commit()
        Try
            If (_Trans IsNot Nothing) Then
                _Trans.Commit()
                _Trans = Nothing
            End If
        Catch ex As Exception
            Me._LastErr = ex.ToString()
            _Trans = Nothing
        End Try
    End Sub

    ''' -------------------------------------------------------------------
    ''' 
    ''' ロールバック
    ''' 
    ''' -------------------------------------------------------------------
    Public Sub Rollback()
        Try
            If (_Trans IsNot Nothing) Then
                _Trans.Rollback()
                _Trans = Nothing
            End If
        Catch ex As Exception
            Me._LastErr = ex.ToString()
            _Trans = Nothing
        End Try
    End Sub

    ''' -------------------------------------------------------------------
    ''' 
    ''' コネクションの解除
    ''' 
    ''' -------------------------------------------------------------------
    Public Sub CloseConnection()
        Try
            If (_Conn IsNot Nothing) Then
                _Conn.Close()
                _Conn = Nothing
            End If
        Catch ex As Exception
            Me._LastErr = ex.ToString()
            _Conn = Nothing
        End Try
    End Sub

    ''' -------------------------------------------------------------------
    ''' 
    ''' SELECT文SQLの実行とDataReaderへの読込
    ''' 
    '''SELECT文SQL
    '''DataReaderへの参照
    '''1行のみの読込指定(true:1行のみ, false:複数行)
    ''' 
    ''' -------------------------------------------------------------------
    Public Function OpenDataReader(ByVal strSQL As String, ByRef Reader As SqlDataReader, _
                                   Optional ByVal fSingleRow As Boolean = False) As Boolean
        Dim functionReturnValue As Boolean = False
        Try
            '戻り値初期化
            functionReturnValue = False

            'DB接続処理
            If _Conn Is Nothing Then
                '未接続の場合に接続する
                _Conn = New SqlConnection(Me._DBConnection)
                _Conn.Open()
            End If

            'トランザクションの指定がされていればコマンドオブジェクトに関連付け
            Dim pCmd As SqlCommand = Nothing
            If (_Trans IsNot Nothing) Then
                pCmd = New SqlCommand(strSQL, _Conn, _Trans)
            Else
                pCmd = New SqlCommand(strSQL, _Conn)
            End If
            _LastSQL = strSQL
            'SQL文の退避
            '---読込オブジェクトに接続---

            '強制的に1行のみ読込??
            If fSingleRow = True Then
                Reader = pCmd.ExecuteReader(CommandBehavior.SingleRow)
                '行数の有無をチェック
                If Reader.HasRows Then
                    If Reader.Read() Then
                        '戻り値初期化
                        functionReturnValue = True
                    End If
                End If
            Else
                '複数行の読込の場合はRead()関数はコールしない(この関数の外側でRead()すること)
                Reader = pCmd.ExecuteReader()
                '行数の有無をチェック
                If Reader.HasRows Then
                    '戻り値初期化
                    functionReturnValue = True
                End If

            End If
        Catch ex As Exception
            'エラーの退避
            _LastErr = ex.Message
            '戻り値エラー
            functionReturnValue = False
        End Try
        Return functionReturnValue
    End Function

    ''' -------------------------------------------------------------------
    ''' 
    ''' DataReaderのクローズ
    ''' 
    '''DataReaderへの参照
    ''' -------------------------------------------------------------------
    Public Sub CloseDataReader(ByRef Reader As SqlDataReader)
        Try
            If (Reader IsNot Nothing) Then
                Reader.Close()
                Reader = Nothing
            End If
        Catch
            Reader = Nothing
        End Try
    End Sub

    ''' -------------------------------------------------------------------
    ''' 
    ''' DML-SQL文の実行
    ''' 
    '''DML-SQL文
    ''' 影響を受けた行数(-1:エラー戻り)
    ''' -------------------------------------------------------------------
    Public Function ExeSQL(ByVal strSQL As String) As Integer
        Dim functionReturnValue As Integer = 0
        Try
            '戻り値初期化
            functionReturnValue = 0
            'DB接続処理
            If _Conn Is Nothing Then
                _Conn = New SqlConnection(Me._DBConnection)
                _Conn.Open()
            End If
            'コマンドオブジェクト処理
            Dim pCmd As New SqlCommand(strSQL, _Conn)
            'SQL文の退避
            _LastSQL = strSQL
            'トランザクションの指定がされていればコマンドオブジェクトに関連付け
            If (_Trans IsNot Nothing) Then
                pCmd.Transaction = _Trans
            End If

            'SQL実行
            functionReturnValue = pCmd.ExecuteNonQuery()
            '戻り値は処理件数
            'オブジェクトの廃棄
            pCmd = Nothing
        Catch ex As Exception
            'エラーの退避
            _LastErr = ex.Message
            'エラーNo取得
            functionReturnValue = -1
        End Try
        Return functionReturnValue
    End Function

    ''' -------------------------------------------------------------------
    ''' 
    ''' DataReaderの結果ItemsをHashtableに変換
    ''' 
    '''DataReader
    ''' Hashtable
    ''' -------------------------------------------------------------------
    Public Function CnvReaderToHashtable(ByVal Reader As SqlDataReader) As Hashtable
        'HashTableの生成
        Dim ht As New Hashtable()
        If Reader Is Nothing Then
            '引数チェックでNULLの場合
            Return ht
        End If
        If Reader.IsClosed Then
            'クローズされている場合
            Return ht
        End If
        Try
            'カラム名
            Dim columnName As String = ""
            'フィールド数の処理
            For i As Integer = 0 To Reader.FieldCount - 1
                'カラム名
                columnName = Reader.GetName(i)
                'HashTableへのReaderの内容Objectを追加
                ht.Add(columnName, Reader.GetValue(i))
            Next
        Catch
            Return ht
        End Try
        Return ht
    End Function
End Class

=====
2015/03/18:の時の情報











PR

コメント

コメントを書く