|
| 1 | +Imports System.Data.SqlClient |
| 2 | + |
| 3 | +Namespace GGlink.Database |
| 4 | + |
| 5 | + Public Class Database |
| 6 | + |
| 7 | + Private host As String = "localhost" |
| 8 | + Private user As String = "user" |
| 9 | + Private password As String = "password" |
| 10 | + Private database As String = "database" |
| 11 | + Private connection As SqlConnection = Nothing |
| 12 | + |
| 13 | + Private Sub New(host As String, user As String, password As String, database As String) |
| 14 | + Me.host = host |
| 15 | + Me.user = user |
| 16 | + Me.password = password |
| 17 | + Me.database = database |
| 18 | + Me.Connect() |
| 19 | + End Sub |
| 20 | + |
| 21 | + Public Function Connect() As Boolean |
| 22 | + Dim connectionString As String = $"Server={host};Database={database};User Id={user};Password={password};" |
| 23 | + connection = New SqlConnection(connectionString) |
| 24 | + connection.Open() |
| 25 | + |
| 26 | + If connection.State <> ConnectionState.Open Then |
| 27 | + Throw New Exception("Failed to connect to the database.") |
| 28 | + End If |
| 29 | + |
| 30 | + Return True |
| 31 | + End Function |
| 32 | + |
| 33 | + Public Function Disconnect() As Boolean |
| 34 | + If connection IsNot Nothing AndAlso connection.State = ConnectionState.Open Then |
| 35 | + connection.Close() |
| 36 | + Return True |
| 37 | + End If |
| 38 | + Return False |
| 39 | + End Function |
| 40 | + |
| 41 | + ' ... Other database operation methods like Query, Select, Insert, etc. |
| 42 | + |
| 43 | + End Class |
| 44 | + |
| 45 | + Public Class DatabaseFactory |
| 46 | + |
| 47 | + Public Shared Function Create() As Database |
| 48 | + Return New Database("localhost", "user", "password", "database") |
| 49 | + End Function |
| 50 | + |
| 51 | + End Class |
| 52 | + |
| 53 | +End Namespace |
| 54 | + |
| 55 | +' Example use: |
| 56 | +Module Main |
| 57 | + |
| 58 | + Sub Main() |
| 59 | + Try |
| 60 | + Dim db As GGlink.Database.Database = GGlink.Database.DatabaseFactory.Create() |
| 61 | + |
| 62 | + ' ... Perform database operations |
| 63 | + |
| 64 | + Catch ex As Exception |
| 65 | + Console.WriteLine("An error occurred: " & ex.Message) |
| 66 | + Finally |
| 67 | + db.Disconnect() |
| 68 | + Console.WriteLine("Disconnected from the database.") |
| 69 | + End Try |
| 70 | + |
| 71 | + End Sub |
| 72 | + |
| 73 | +End Module |
0 commit comments