How to Connect to MS SQL Using VBScript

Written by jim campbell
  • Share
  • Tweet
  • Share
  • Email

Visual Basic Scripting, or VBS, lets you connect to your internal database to retrieve data for your users. VBS is typically used by Windows network administrators to set up preferences on a user's computer and map network drives. You connect to a database using VBS to retrieve user preferences stored in the Microsoft SQL Server database tables. The object used to connect is called "ADO," which is a Microsoft connection object available for each Microsoft programming language.

Skill level:

Other People Are Reading


  1. 1

    Right-click your VBS script file and select "Open With." Double-click "Notepad" to open the file in your text editor. If you have a third-party editor, double-click it instead.

  2. 2

    Create your ADO variables. The ADO object variables are used to connect to your database. The object contains the functions and properties used to connect in a Windows environment. Type the following code in your file:

    Set conn = CreateObject("ADODB.Connection")

    Set rs = CreateObject("ADODB.Recordset")

  3. 3

    Create the connection. The "connection" object you've created in Step 2 allows you to connect to the database. You must specify your database server, username and password. Type the following code in the editor:

    conn.Open "Provider=SQLOLEDB;Data Source=sql_server;Trusted_Connection=Yes;Initial Catalog=db_name;User ID=user;Password=pass;"

    Replace "sql_server" with your MS SQL server name. Replace "db_name" with the name of your database, and replace "user" and "pass" with the SQL Server username and password set up on the database.

  4. 4

    Retrieve records from the database. Now that you have a connection, you can query the tables for records. Below is an example of querying for an employee's name:

    query = "select name from employees"

    rs.Open query, con, adOpenStatic, adLockOptimistic

    Replace the query variable string with your own query.

  5. 5

    Press "Ctrl" and "S" to save your changes. Double-click the VBS file to execute it in Windows and test the new code.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.