Advertisement
Guest User

VB.NET Database Connection

a guest
May 7th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.82 KB | None | 0 0
  1. Imports System.Data.OleDb
  2. Imports System.IO
  3.  
  4. Public Class DB
  5.  
  6.     'Maintain a connection
  7.     Public Shared connection As OleDbConnection
  8.  
  9.     Public Shared reader As OleDbDataReader
  10.     Public Shared reader2 As OleDbDataReader
  11.  
  12.     Public Shared Sub connectToDB()
  13.         'Connect to database
  14.         Try
  15.             'Build a connection
  16.  
  17.             ' Connection String For Microsoft Office/Access 2007,2010,2013
  18.             'Provider=Microsoft.ACE.OLEDB.12.0
  19.  
  20.             connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
  21.                                                  "Data Source=|DataDirectory|\Database\{MyDatabaseFilename}.accdb; Jet OLEDB:Database Password={MyPassword};")
  22.  
  23.             'Opens the connection
  24.             connection.Open()
  25.         Catch e As OleDb.OleDbException
  26.             MsgBox(e.Message, Error_Code.Code_0x0001, Error_Code.Msg_0x03)
  27.         Catch ex As Exception
  28.             MsgBox(ex.Message)
  29.             'close the application
  30.             MsgBox(ex.Message, Error_Code.Code_0x0002, Error_Code.Code_0x0002)
  31.         End Try
  32.     End Sub
  33.  
  34.     Public Shared Sub disconnectFromDB()
  35.         Try
  36.             'Close the connection
  37.             connection.Close()
  38.         Catch ex As OleDb.OleDbException
  39.             MsgBox(ex.Message, Error_Code.Msg_0x7, Error_Code.Msg_0x03)
  40.         End Try
  41.     End Sub
  42.  
  43.     Public Shared Sub CompactAndRepair(ByVal accessFile As String, ByVal app As Microsoft.Office.Interop.Access.Dao.DBEngine)
  44.         Dim tempFile As String = Path.Combine(Path.GetDirectoryName(accessFile), Path.GetRandomFileName() + Path.GetExtension(accessFile))
  45.         app.CompactDatabase(accessFile, tempFile, False)
  46.         Dim temp As FileInfo = New FileInfo(tempFile)
  47.         temp.CopyTo(accessFile, True)
  48.         temp.Delete()
  49.     End Sub
  50.  
  51. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement