memberlogin
contactus
randomfacts

Connecting to sql server with vbscript (asp)

The code below shows how to connect to a sql server database using vbscript.  It starts with the isobject if statement to check and see if the connection is already open - if it is not then it goes ahead and opens up the database connection.  All that you need to do is to update the variables for data source (server name - ipaddress or server name), uid - database user id, pwd - database password and database - the name of the database.  It\'s generally a good idea to put this code in an included file so that if anything changes with the database name, server name, user_id or password - for example if you change website hosts - then you only need to change it once - instead of opening up every file with this connection string...

<%
If Not IsObject(cnn) Then
 \'Open the connection to the database
 set cnn = server.createobject("ADODB.Connection")
 cnn.open "PROVIDER=SQLOLEDB;DATA SOURCE=sql server name;UID=db_userid;PWD=db_password;DATABASE=database_name "
End If
%>

 

Now to close the database you would use the code snippet below.  You check to see if the database connection string is open and if it is you will use 2 lines of code to close the connection.

<%
If IsObject(cnn) Then
  cnn.Close
  Set cnn = Nothing
End If
%>