HowTo Connect HTML with MS SQL

This example script shows you how to get started in web/database development by connecting an HTML page to an MS SQL database via VbScript.

<SCRIPT LANGUAGE="VBScript">

   Dim objConn
   Dim objRec
   Dim sIn
   Dim Query

   ' Put an SQL query into a string
   Query = "SELECT * FROM MyTable WHERE name LIKE 'target%'"

   ' This is our connection to the MS SQL Database
   strConnect = "Server=TESTING1;Database=MSSQLDB;UID=user;PWD=password"

   ' We access the database thru an ADO connection
   Set objConn = CreateObject ("ADODB.connection")

   ' This tells which provider / driver to use
   objConn.Provider="SQLOLEDB"

   ' Opens the database connection
   objConn.Open strConnect

   ' Creates a recordset to hold the data coming back from the query
   Set objRec = CreateObject ("ADODB.Recordset")

   ' Causes the query to execute
   objRec.Open Query, objConn

   ' Output field names
   document.write (objRec.Fields(0).Name)
   document.write (" ")
   document.write (objRec.Fields(1).Name)
   document.write (" ")
   document.write (objRec.Fields.Count)
   document.write ("<br />")

   ' Output each record
   do while not objRec.EOF
      document.write (objRec.Fields(0).Value)
      document.write (" ")
      document.write (objRec.Fields(1).Value)
      document.write ("<br />")
      objRec.MoveNext
   loop

   ' Close the recordset
   objRec.close
   set objRec = nothing

   ' Close the database connection
   objConn.close
   set objConn = nothing

</SCRIPT>

Leave a Reply