Public Function ConnectToDB(Optional bUseDSN As Boolean = False, _
Optional sDSNName As String, _
Optional sUserName As String = vbNullString, _
Optional sPass As String = vbNullString) As Integer
'This function will return:
' 1: Connect is successfull
' 0: Can not connect to database or error
'The ObjectStateEnum constants defined in ADO
'.adStateClosed | Means the connection is closed
'.adStateOpen | Means the connection is open
'.adStateConnecting | Means the object is in the process of making a connection
'.adStateExecuting | Means the connection is executing a command
Dim sConnect As String
Dim lAttempt As Long
Dim iConnectFirstTimes As Integer
On Error GoTo ErrorHandler
'Check the gcnAcess before open
'gcnAccess.State = ObjectStateEnum.adStateOpen is openning
'Not gcnAccess Is Nothing, we have create the gcnAccess variable
If (gcnAccess.State = ObjectStateEnum.adStateOpen) And (Not gcnAccess Is Nothing) Then
'i.e has connected to database
'tuc la da ket noi voi CSDL
ConnectToDB = eTinhTrangKetNoi.KetNoiThanhCong
gcnAccess.Close
GoTo ErrorExit
End If
'Suppose that can not connect to database
'Gia su rang khong the ket noi voi CSDL
ConnectToDB = eTinhTrangKetNoi.KetNoiKhongThanhCong
iConnectFirstTimes = GetIni("DSN", "FIRSTTIME")
If CInt(iConnectFirstTimes) = 1 Then
iConnectFirstTimes = 1 'is the first times to connect/Neu bang 1 tuc la lan dau tien connect
Else
iConnectFirstTimes = 0 'does not the first times to connect/Neu khac 1 tuc la day khong phai lan dau tien
End If
sConnect = GetConStr(iConnectFirstTimes, bUseDSN, sDSNName, sUserName, sPass)
If sConnect = vbNullString Then
'If sConnect = vbNullString, then can not connect to database
GoTo ErrorExit
End If
With gcnAccess
.Mode = adModeReadWrite
.ConnectionTimeout = 30 'Neu sau thoi gian nay ma khong ket noi duoc se bao loi
.CursorLocation = adUseClient
.ConnectionString = sConnect
.Open
End With
ConnectToDB = eTinhTrangKetNoi.KetNoiThanhCong
'Close the connection to enable connection pooling
gcnAccess.Close
ErrorExit:
Exit Function
ErrorHandler:
'We will try to make the connection 3 times before bailing out
If lAttempt < 3 And gcnAccess.Errors.Count > 0 Then
If gcnAccess.Errors(0).NativeError = 17 Then
lAttempt = lAttempt + 1
Resume
End If
Else
'If more than 3 times then
ConnectToDB = eTinhTrangKetNoi.KetNoiKhongThanhCong 'i.e can not connect to Database
End If
If bCentralErrorHandler(mcsModName, "ConnectToDB", , False) Then
Stop
Resume
Else
Resume ErrorExit
End If
End Function