VB.NETからSQL Serverへの接続する為のクラスです。
CustomDBConnection.vb(クラス)
Option Strict On
Imports System.Data.SqlClient
Public Class CustomDBConnection
Private _connection As SqlConnection = Nothing
Private _transaction As SqlTransaction = Nothing
#Region "プロパティ"
Public Property CONN() As SqlConnection
Get
Return _connection
End Get
Set(ByVal value As SqlConnection)
_connection = value
End Set
End Property
Public Property TRANS() As SqlTransaction
Get
Return _transaction
End Get
Set(ByVal value As SqlTransaction)
_transaction = value
End Set
End Property
#End Region
Public Sub Connect()
Try
If _connection Is Nothing Then
_connection = New SqlConnection
End If
Dim strConnection As String = ""
strConnection = strConnection & "Server=localhost"
strConnection = strConnection & ";Database=testdb"
strConnection = strConnection & ";User ID=matsui"
strConnection = strConnection & ";Password=123"
_connection.ConnectionString = strConnection
_connection.Open()
Catch ex As Exception
Throw New Exception("データベース接続エラー", ex)
End Try
End Sub
Public Sub Disconnect()
Try
If _connection.State <> ConnectionState.Closed Then
_connection.Close()
End If
Catch ex As Exception
Throw New Exception("データベース切断エラー", ex)
End Try
End Sub
Public Sub BeginTransaction()
Try
_transaction = _connection.BeginTransaction()
Catch ex As Exception
Throw New Exception("トランザクション開始エラー", ex)
End Try
End Sub
Public Sub CommitTransaction()
Try
If _transaction Is Nothing = False Then
_transaction.Commit()
End If
Catch ex As Exception
Throw New Exception("コミットエラー", ex)
Finally
_transaction = Nothing
End Try
End Sub
Public Sub RollbackTransaction()
Try
If _transaction Is Nothing = False Then
_transaction.Rollback()
End If
Catch ex As Exception
Throw New Exception("ロールバックエラー", ex)
Finally
_transaction = Nothing
End Try
End Sub
End Class
使い方

Windows フォーム
Try
Dim db As New CustomDBConnection
db.Connect()
db.BeginTransaction()
db.CommitTransaction()
Catch ex As Exception
db.RollbackTransaction()
Finally
db.Disconnect()
End Try