Friday, May 6, 2016

MSSQL connection using ADODB connection and Recordset

'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL
'define the connection string, specify database driver
ConnString="DRIVER={SQL Server};SERVER=server01.domian.com;UID=service_account;" & _
PWD=P@ssw0rd;DATABASE=Database_name
'declare the SQL statement that will query the database
SQL = "Select * from table"

'create an instance of the ADO connection and recordset objects
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("ADODB.Recordset")
'Open the connection to the database
Connection.Open ConnString
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection
Wscript.Echo "User" &VbTab& "AppName" &VbTab& "nDays"
'first of all determine whether there are any records
If Recordset.EOF Then
Wscript.Echo ("No records returned.")
Else
'if there are records then loop through the fields
Do While NOT Recordset.Eof  
Wscript.Echo Recordset.Fields(0) &VbTab& Recordset.Fields(1) &VbTab& Recordset.Fields(2)
'Wscript.Echo VbNewline   
Recordset.MoveNext
Loop
End If
'close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing

No comments:

Post a Comment