Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Database connection testing 1

Status
Not open for further replies.

gregmosu

Programmer
Jul 8, 2002
117
US
Is there a quick way to test if this connection is open... like a try/catch block, or maybe the .Open function returns a result. I couldnt find anything online about it.

Thanks in advance!

Code:
Set objConnection = CreateObject("ADODB.Connection")
            
objConnection.Open "Driver={SQL Server};SERVER=" & server & ";Database=" & database & ";Uid=" & username & ";Pwd=" & password & ""
 
Try something like:

Code:
If objConnection.State = adStateOpen Then
' do whatever
End If

The ObjectStateEnum constants are:

adStateClosed = 0 'The object is closed
adStateOpen = 1 'The object is open
adStateConnecting = 2 'The object is connecting
adStateExecuting = 4 'The object is executing a command
adStateFetching = 8 'The rows of the object are being retrieved

I would think the Open method would throw an error if a connection couldn't be made.

HTH
Mike
 
Thanks for the reply Mike. That worked, didnt do quite what I wanted though. I did find a way to catch errors... but it seems to not work all the time. Heres what I came up with...

Call this on Workbook_open

Code:
Private Sub DB_Test()
    
    On Error GoTo CatchError
    
    Set objTestConnection = CreateObject("ADODB.Connection")
    Dim server, database, username, password, port
    server = Sheets("DB").Range("B1").Value
    database = Sheets("DB").Range("B2").Value
    username = Sheets("DB").Range("B3").Value
    password = Sheets("DB").Range("B4").Value
        
    objTestConnection.Open "Driver={SQL Server};SERVER=" & server & ";Database=" & database & ";Uid=" & username & ";Pwd=" & password & ""
    objTestConnection.Close
    Set objTestConnection = Nothing
    UserForm1.Show
    
NormalExit:
    Exit Sub
CatchError:
    MsgBox "Unable to establish database connection."
    Sheets("DB").Visible = True
    GoTo NormalExit
End Sub
 
Can you clarify what you mean by
it seems to not work all the time
What doesn't work? Are you not getting the error message when you think you should?


Incidentally, you might want to move the line destroying the object variable as so:
Code:
NormalExit:
   Set objTestConnection = Nothing 
   Exit Sub
so that it is destroyed whether an error occurs or not. Or, if you will use this connection elsewhere (I assume so or why would you need to test the connection [wink]) don't destroy it at all until you are finished using it.


Regards,
Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top