Skip to content

Instantly share code, notes, and snippets.

@facebookegypt
Created May 24, 2020 08:09
Show Gist options
  • Save facebookegypt/39b578d1a15738897d9124586adac4d1 to your computer and use it in GitHub Desktop.
Save facebookegypt/39b578d1a15738897d9124586adac4d1 to your computer and use it in GitHub Desktop.
Imports System.Data.OleDb
Public Class ThisClass
Private ConnectionString As String
Private CN As OleDbConnection = New OleDbConnection
'This function Returns the Oledb Provider for your Project
'I.e: if you have Office 2016 installed, it will return :
'Microsoft.ACE.OLEDB.16.0
Public Function FindProvider() As String
Dim Provider As String = String.Empty
Dim reader = OleDbEnumerator.GetRootEnumerator()
Dim list = New List(Of String)
While reader.Read()
For i = 0 To reader.FieldCount - 1
If reader.GetName(i) = "SOURCES_NAME" Then
list.Add(reader.GetValue(i).ToString())
End If
Next
End While
Return Nothing
reader.Close()
For Each provider In list
If Provider.StartsWith("Microsoft.ACE.OLEDB") Then
Provider = Provider.ToString()
Return Provider
Else
Return Nothing
Exit Function
End If
Next
End Function
'This function is to validate connection to the database *.accdb
Public Function DBConnected(ByVal DBLocation As String, ByVal DBPass As String) As Boolean
ConnectionString =
("Provider=" & FindProvider() & ";Data Source=" & DBLocation & ";" _
& "Jet OLEDB:Database Password = '" & DBPass & "'; " _
& "Persist Security Info=False;")
CN.ConnectionString = ConnectionString
If CN.State = ConnectionState.Open Then CN.Close()
Try
CN.Open()
Catch ex As OleDbException
MsgBox("Error Database connection : " & ex.Message, MsgBoxStyle.Critical)
Result = False
Return Result
Exit Function
End Try
Result = True
Return Result
End Function
'Ofcourse this is not secure connection String, but just an example.
'You should always use Configuration Files to manage Database Connections.
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment