NonSoft

System.Data.OleDbによるDBインタフェース
のサンプル(VB.NET)


 サンプル(ソース/コード)
<このサンプルの概要>
System.Data.OleDbによるDBインタフェースのサンプル(VB.NET)です。
System.Data.OleDbは汎用のADOクラスです。本サンプルはSystem.Data.OleDbの基本機能だけをシンプルに
クラス化しています。基本機能としてはDB接続、DB切断、DB検索、DB更新、トランザクション開始、コミット、
ロールバックがあります。これ以外の機能を使う事は殆ど無いと思います。
このサンプルはローカルのSQLサーバーに接続するサンプルになっています。

ACCESSやORACLEに接続する時のプロバイダは以下に記述して置きます。
ACCESS:Provider="Microsoft.Jet.OLEDB.4.0"
ORACLE:Provider="MSDAORA"

(注1)ACCESSの時はDatabase/User ID/Passwordの指定はいりません。
(注2)ORACLEの時はDatabaseの指定はいりません。

<関連情報>
System.Data.SqlClient、System.Data.OleDb、System.Data.Odbcの比較が出来ます。
ほとんど同じと言うことは、インタフェースクラスを作って派生させるのがスジですね。
System.Data.SqlClientによるDBインタフェースのサンプル(VB.NET)
System.Data.OdbcによるDBインタフェースのサンプル(VB.NET)
データベース関係のその他のサンプル(VB6/VB.NET/C#.NET)

★クラス(OleDbIf.vb)
Imports System.Data.OleDb

Public Class OleDbIf
    ''' 
    ''' SQLコネクション
    ''' 
    Private _con As OleDbConnection = Nothing

    ''' 
    ''' トランザクション・オブジェクト
    ''' 
    ''' 
    Private _trn As OleDbTransaction = Nothing

    ''' 
    ''' DB接続
    ''' 
    ''' データソース名
    ''' データベース名
    ''' ユーザーID
    ''' パスワード
    ''' タイムアウト値
    ''' 
    Public Sub Connect(Optional ByVal dsn As String = "localhost", _
                       Optional ByVal dbn As String = "master", _
                       Optional ByVal uid As String = "sa", _
                       Optional ByVal pas As String = "", _
                       Optional ByVal tot As Integer = -1)

        Try
            If _con Is Nothing Then
                _con = New OleDbConnection
            End If

            Dim cst As String = ""
            cst = cst & "Provider=SQLOLEDB"
            cst = cst & ";Data Source=" & dsn
            cst = cst & ";Database=" & dbn
            cst = cst & ";User ID=" & uid
            cst = cst & ";Password=" & pas
            If tot > -1 Then
                '_con.ConnectionTimeout = tot
                cst = cst & ";Connect Timeout=" & tot.ToString
            End If
            _con.ConnectionString = cst

            _con.Open()
        Catch ex As Exception
            Throw New Exception("Connect Error", ex)
        End Try
    End Sub

    ''' 
    ''' DB切断
    ''' 
    Public Sub Disconnect()
        Try
            _con.Close()
        Catch ex As Exception
            Throw New Exception("Disconnect Error", ex)
        End Try
    End Sub

    ''' 
    ''' SQLの実行
    ''' 
    ''' SQL文
    ''' タイムアウト値
    ''' 
    ''' 
    Public Function ExecuteSql(ByVal sql As String, _
                               Optional ByVal tot As Integer = -1) As DataTable
        Dim dt As New DataTable

        Try
            Dim sqlCommand As New OleDbCommand(sql, _con, _trn)

            If tot > -1 Then
                sqlCommand.CommandTimeout = tot
            End If

            Dim adapter As New OleDbDataAdapter(sqlCommand)

            adapter.Fill(dt)
            adapter.Dispose()
            sqlCommand.Dispose()
        Catch ex As Exception
            Throw New Exception("ExecuteSql Error", ex)
        End Try

        Return dt
    End Function

    ''' 
    ''' トランザクション開始
    ''' 
    ''' 
    Public Sub BeginTransaction()
        Try
            _trn = _con.BeginTransaction()
        Catch ex As Exception
            Throw New Exception("BeginTransaction Error", ex)
        End Try
    End Sub

    ''' 
    ''' コミット
    ''' 
    ''' 
    Public Sub CommitTransaction()
        Try
            If _trn Is Nothing = False Then
                _trn.Commit()
            End If
        Catch ex As Exception
            Throw New Exception("CommitTransaction Error", ex)
        Finally
            _trn = Nothing
        End Try
    End Sub

    ''' 
    ''' ロールバック
    ''' 
    ''' 
    Public Sub RollbackTransaction()
        Try
            If _trn Is Nothing = False Then
                _trn.Rollback()
            End If
        Catch ex As Exception
            Throw New Exception("RollbackTransaction Error", ex)
        Finally
            _trn = Nothing
        End Try
    End Sub

    ''' 
    ''' ファイナライズ
    ''' 
    ''' 
    Protected Overrides Sub Finalize()
        Disconnect()
        MyBase.Finalize()
    End Sub
End Class

★フォームモジュール(Form1.vb)
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows フォーム デザイナで生成されたコード "
' 省略
' ボタンを2つ追加してお試しください
#End Region

    Private Sub Button1_Click( _
        ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim db As New OleDbIf
        Dim tb As DataTable
        Dim i As Integer
        db.Connect()
        tb = db.ExecuteSql("select col1,col2,col3 from test")
        For i = 0 To tb.Rows.Count - 1
            System.Diagnostics.Trace.WriteLine( _
                tb.Rows(i).Item("col1").ToString() & ":" & _
                tb.Rows(i).Item("col2").ToString() & ":" & _
                tb.Rows(i).Item("col3").ToString())
        Next
        db.Disconnect()
    End Sub

    Private Sub Button2_Click( _
        ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim db As New OleDbIf
        db.Connect()
        db.BeginTransaction()
        db.ExecuteSql( _
            "insert into test(col1,col2,col3) " & _
            "values('1234567890',9,'2007-03-04 05:06:07')")
        db.CommitTransaction()
        db.Disconnect()
    End Sub
End Class