Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Visual Basic (Microsoft) Versions 5/6 FAQ


Connecting to SQL Server Programmatically by BrianLW
Posted: 12 Feb 04 (Edited 17 Feb 04)

This is a very basic example of how to connect to a SQL Server. The Recordset object and Connection object have many more properties than these.

For more information about the other properties, please go to:

Begin with making sure your Project has a reference to 'Microsoft ActiveX Data Objects 2.x Library' where x is (preferably) the highest number.

' **** Create Connection and Recordset Objects ****
Dim cnConn As ADODB.Connection
Dim rs As ADODB.Recordset

' **** Instantiate the new objects ****
Set cnConn = New ADODB.Connection
Set rs = New ADODB.Recordset

' **** Set up connection String    ****
With cnConn
    .Provider = "SQLOLEDB.1"
    .Properties("Data Source").Value = "SQLServerName"
    .Properties("User ID").Value = "UserName"
    .Properties("Password").Value = "Password"
    .Properties("Initial Catalog").Value = "DatabaseName"
    .CursorLocation = adUseClient
    .ConnectionTimeout = 0
End With

' **** String to pass to the connection to get records back ****
strSQL = "SELECT * FROM TableName"

' **** Open Records for readonly ****
rs.Open strSQL, cnConn, adOpenStatic, adLockReadOnly

Do what you need to with the recordset.

When you are finished with it:

' **** Close Objects ****

If you are completely finished with them:

' **** Destroy objects ****
Set rs = Nothing
Set cnConn = Nothing

Back to Visual Basic (Microsoft) Versions 5/6 FAQ Index
Back to Visual Basic (Microsoft) Versions 5/6 Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close