Issue with running vbs script to execute ASP page through Windows Task Scheduler - asp-classic

I am trying to execute an ASP page through a vbs file being triggered through Windows Task Scheduler.
The Task is completing without errors, however it completes immediately and is not updating my database. If I run the ASP directly through the browser it does work correctly. Ideas?
VBS File Code:
Dim url, xmlhttp
url = "http://localhost/adr-gateway/index-sysmon-cdDB.asp" ' ASP script to run
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET", url, false
xmlhttp.send ""
set xmlhttp = nothing
ASP File Code: Basically pulling data from 1 database and inserting it into another.
<%
'===================================================================================================================
'GET TOTAL NUMBER OF COMPLETED IMPORTS IN LAST HOUR
'===================================================================================================================
'MY SQL - DEFINE CONNECTION STRING & SPECIFY DB DRIVER
ConnString = "DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=174.xx.xx.xxx; DATABASE=content_distributor; " &_
"UID=admin;PASSWORD=admin; PORT=3306 ; OPTION=3"
'CREATE INSTANCE OF ADO CONNECTION AND RECORDSET OBJECTS
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'OPEN CONNECTION TO DB
Connection.Open ConnString
'SQL STATEMENT TO QUERY DB
SQL = "SELECT * FROM jobs WHERE DATE_ADD(updated_at, INTERVAL 60 MINUTE) > NOW() AND job_type='IMPORT' AND state='COMPLETE'"
'OPEN RECORDSET AND RETURN SQL QUERY
Recordset.Open SQL,Connection
'CHECK FOR RECORDS
If Recordset.EOF Then
msg = "No Records Present in Database"
Else
'SET COUNT VARIABLE
importCount = 0
'IF THERE ARE RECORDS LOOP THROUGH THE DB
Do While NOT Recordset.Eof
importCount = importCount + 1
Recordset.MoveNext
Loop
End If
'CLOSE CONNECTION AND RECORDSET TO FREE UP CONNECTIONS
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
'===================================================================================================================
'GET TOTAL NUMBER OF COMPLETED COPY JOBS IN LAST HOUR
'===================================================================================================================
'MY SQL - DEFINE CONNECTION STRING & SPECIFY DB DRIVER
ConnString = "DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=174.75.78.150; DATABASE=content_distributor; " &_
"UID=admin;PASSWORD=admin; PORT=3306 ; OPTION=3"
'CREATE INSTANCE OF ADO CONNECTION AND RECORDSET OBJECTS
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'OPEN CONNECTION TO DB
Connection.Open ConnString
'SQL STATEMENT TO QUERY DB
SQL = "SELECT * FROM jobs WHERE DATE_ADD(updated_at, INTERVAL 60 MINUTE) > NOW() AND job_type='COPY' AND state='COMPLETE'"
'OPEN RECORDSET AND RETURN SQL QUERY
Recordset.Open SQL,Connection
'CHECK FOR RECORDS
If Recordset.EOF Then
msg = "No Records Present in Database"
Else
'SET COUNT VARIABLE
copyCount = 0
'IF THERE ARE RECORDS LOOP THROUGH THE DB
Do While NOT Recordset.Eof
copyCount = copyCount + 1
Recordset.MoveNext
Loop
End If
'CLOSE CONNECTION AND RECORDSET TO FREE UP CONNECTIONS
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
'===================================================================================================================
'GET TOTAL NUMBER OF COMPLETED DELETE JOBS IN LAST HOUR
'===================================================================================================================
'MY SQL - DEFINE CONNECTION STRING & SPECIFY DB DRIVER
ConnString = "DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=174.75.78.150; DATABASE=content_distributor; " &_
"UID=admin;PASSWORD=admin; PORT=3306 ; OPTION=3"
'CREATE INSTANCE OF ADO CONNECTION AND RECORDSET OBJECTS
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'OPEN CONNECTION TO DB
Connection.Open ConnString
'SQL STATEMENT TO QUERY DB
SQL = "SELECT * FROM jobs WHERE DATE_ADD(updated_at, INTERVAL 60 MINUTE) > NOW() AND job_type='DELETEALL' AND state='COMPLETE'"
'OPEN RECORDSET AND RETURN SQL QUERY
Recordset.Open SQL,Connection
'CHECK FOR RECORDS
If Recordset.EOF Then
msg = "No Records Present in Database"
Else
'SET COUNT VARIABLE
deleteCount = 0
'IF THERE ARE RECORDS LOOP THROUGH THE DB
Do While NOT Recordset.Eof
deleteCount = deleteCount + 1
Recordset.MoveNext
Loop
End If
'CLOSE CONNECTION AND RECORDSET TO FREE UP CONNECTIONS
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
'===================================================================================================================
'GET TOTAL NUMBER OF FAILED JOBS IN LAST HOUR
'===================================================================================================================
'MY SQL - DEFINE CONNECTION STRING & SPECIFY DB DRIVER
ConnString = "DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=174.75.78.150; DATABASE=content_distributor; " &_
"UID=admin;PASSWORD=admin; PORT=3306 ; OPTION=3"
'CREATE INSTANCE OF ADO CONNECTION AND RECORDSET OBJECTS
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'OPEN CONNECTION TO DB
Connection.Open ConnString
'SQL STATEMENT TO QUERY DB
SQL = "SELECT * FROM jobs WHERE DATE_ADD(updated_at, INTERVAL 60 MINUTE) > NOW() AND state='FAILED'"
'OPEN RECORDSET AND RETURN SQL QUERY
Recordset.Open SQL,Connection
'CHECK FOR RECORDS
If Recordset.EOF Then
msg = "No Records Present in Database"
failedCount = "0"
Else
'SET COUNT VARIABLE
failedCount = 0
'IF THERE ARE RECORDS LOOP THROUGH THE DB
Do While NOT Recordset.Eof
failedCount = failedCount + 1
Recordset.MoveNext
Loop
End If
'CLOSE CONNECTION AND RECORDSET TO FREE UP CONNECTIONS
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
'Create an ADO connection object
Set adoCon = Server.CreateObject("ADODB.Connection")
'Set an active connection to the Connection object using a DSN-less connection
adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("DB/TS-GATEWAY.mdb")
'Create an ADO recordset object
Set rsAdd = Server.CreateObject("ADODB.Recordset")
'Initialise the strSQL variable with an SQL statement to query the database
strSQL = "SELECT * FROM CD_Health;"
'Set the cursor type we are using so we can navigate through the recordset
rsAdd.CursorType = 2
'Set the lock type so that the record is locked by ADO when it is updated
rsAdd.LockType = 3
'Open the recordset with the SQL query
rsAdd.Open strSQL, adoCon
'Tell the recordset we are adding a new record to it
rsAdd.AddNew
'Add a new record to the recordset
rsAdd.Fields("importCount") = importCount
rsAdd.Fields("copyCount") = copyCount
rsAdd.Fields("deleteCount") = deleteCount
rsAdd.Fields("failedCount") = failedCount
'Write the updated recordset to the database
rsAdd.Update
'Reset server objects
rsAdd.Close
Set rsAdd = Nothing
Set adoCon = Nothing
%>

Related

Parameterizing sql in asp

I'm not terribly familiar with asp, but I have one project with a page of it.
<%
'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL
Dim userName
userName = Request.Form("userName")
'define the connection string, specify database driver
ConnString="JJJJJ"//connection information
'declare the SQL statement that will query the database
SQL = "SELECT info AS Lunch, "
SQL = SQL & "FROM dbo.AgentActivityLog WHERE UserId = '" & userName & "'
'create an instance of the ADO connection and recordset objects
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.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
'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'process record
Next
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
%>
How do I parameterize the username? I have no way to debug, no knowledge of how this language works, so whatever I tried failed and I have no idea why.
I would suggest you look at the Answer on following link as it will fill in the answers you seek:
VBA, ADO.Connection and query parameters
From the code provided critical missing piece is the ADODB.Command for the SQL to actually be run and to add the parameter the query you would :
Set Param = Command.CreateParameter("#userid",adVarChar,adParamInput)
Param.Value = userName
Command.Paramters.Append Param

Creating dynamic ADODB connections in Classic ASP

I have a list of Database connection strings, Database Name. These databases have the same table structure. What I am trying to do is dynamically create a connection to each one, add/delete/modify a table, however, if an error pops up anywhere, then RollbackTrans, else, CommitTrans.
My basic question to get my on the correct path is this:
Is this code possible in Classic ASP to make Dynamically named connections?
'create the dynamic object
execute("Set Con" & index & " = Server.CreateObject(""ADODB.connection"")")
'connect to the dynamic object
execute("Con" & index & ".Open " & DBString(index))
The error I get is 'Expected end of statement' on the .open line (the last one)
This might do the trick: Just use an array of connection strings. From this you create an array of connections. Then you can iterate over this array and send your commands to the separate databases.
dim connectionStrings(1)
dim connections(1)
dim curConn
connectionStrings(0) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=master;uid=youruser;pwd=yourpwd"
connectionStrings(1) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=model;uid=youruser;pwd=yourpwd"
for curConn = 0 to ubound( connectionStrings)
set connections(curConn) = Server.CreateObject("ADODB.Connection")
connections(curConn).Open connectionStrings(curConn)
next
dim cmd : cmd = "select ##servername, db_name()"
for curConn = 0 to ubound( connectionStrings)
dim rs
set rs = connections(curConn).Execute( cmd)
Response.write( rs( 0) & ":" & rs(1) & "<br />")
rs.close
set rs = nothing
next
for curConn = 0 to ubound( connectionStrings)
call connections(curConn).Close
set connections(curConn) = nothing
next
Mysql Dynamic Connection String , sample for t=1 to 4 , four different database connection conns(t)
dim conns(4)
Set Conns(1)=Server.Createobject("ADODB.Connection")
Conns(1).Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;port=3306;DATABASE=dbname;UID=root;PASSWORD=pass;OPTION=3"
Conns(1).Execute "SET NAMES 'latin5'"
Conns(1).Execute "SET CHARACTER SET latin5"
Conns(1).Execute "SET COLLATION_CONNECTION = 'latin5_turkish_ci'"

insert query in MySQL error

I have create a function. When the user click the button, data will automatic inset into order table. But it keep give me error. I use the way to do my register page is working fine.
Error Message:
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order(UserId, OrderStatus, OrderDate) values ('kit', 'Pending', '2014-12-08 22:4' at line 1
If Session("OrderId") Is Nothing Then
Dim conn As New MySqlConnection
conn.ConnectionString = "server = localhost; user id = root; password = root; database = db_fyp"
Dim com As New MySqlCommand
conn.Open()
Dim query As String
query = "insert into order(UserId, OrderStatus, OrderDate) values (#UserId, #OrderStatus, #OrderDate)"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#UserId", Session("Username"))
com.Parameters.AddWithValue("#OrderStatus", "Pending")
com.Parameters.AddWithValue("#OrderDate", Now())
com.ExecuteNonQuery()
conn.Close()
End If
Return Nothing
End Function
Order is a reserved keyword in any SQL language known. I really suggest to change that table name to something less problematic. In the meantime you could change the query to
query = "insert into `order` (UserId, OrderStatus, OrderDate) " & _
"values (#UserId, #OrderStatus, #OrderDate)"

sqlite windows unable to insert -

I'm seeing an error trying to insert new records to q sqlite3 db via Classic ASP, where updates and reads work fine.
ODBC driver does not support the requested properties.
/engine/includes/ajaxed/class_database/database.asp, line 160
which basically boils down to your standard:
connectionString = "DRIVER=SQLite3 ODBC Driver;Database=" & server.mappath("/site.db") & ";LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;
set connection = server.createObject("ADODB.connection")
connection.open(connectionString)
set aRS = server.createObject("ADODB.Recordset")
' error raised on next line
aRS.open tablename, connection, adOpenKeyset, adLockPessimistic, adCmdTable
Permissions are correct (basically that file has everyone full control, including IUSR), and I've had to change the db to no journalling due to this problem (Exception Message: Some kind of disk I/O error occurred); reads and updates to existing records are fine.
I am using the current version of the http://www.ch-werner.de/sqliteodbc/ 32-bit odbc driver.
I've tried setting other recordset options like (adOpenKeyset, adLockOptimistic); no luck, same error message. I've attempted a read of the sqliteodbc code to see what the supported properties /are/, but couldn't work it out.
The following code works for me:
Const adOpenKeyset = 1
Const adLockPessimistic = 2
Const adCmdTable = 2
db = "C:\test.db"
connectionString = "DRIVER=SQLite3 ODBC Driver;Database=" & db & _
";LongNames=0;Timeout=1000;NoTXN=0;SyncPragma=NORMAL;StepAPI=0;"
Set conn = CreateObject("ADODB.Connection")
conn.Open connectionString
Set rs = CreateObject("ADODB.Recordset")
tablename = "a"
rs.Open tablename, conn, adOpenKeyset, adLockPessimistic, adCmdTable
cols = Array("id", "name")
values = Array(3, "baz")
rs.AddNew cols, values
rs.Update
Example:
C:\>sqlite3 test.db "CREATE TABLE a (id integer, name varchar(20));"
C:\>sqlite3 test.db "INSERT INTO a VALUES (1, 'foo');"
C:\>sqlite3 test.db "INSERT INTO a VALUES (2, 'bar');"
C:\>sqlite3 test.db "SELECT * FROM a;"
1|foo
2|bar
C:\>cscript //NoLogo C:\path\to\sample.vbs
C:\>sqlite3 test.db "SELECT * FROM a;"
1|foo
2|bar
3|baz

Microsoft ODBC driver for Oracle Syntax error or access violation (-2147217900)

I have a large VB program that connects to Oracle database.
strCn = "Driver={Microsoft ODBC for Oracle};" & _
"SERVER=PSPROD;"
Set Cn = New ADODB.Connection
Cn.ConnectionString = strCn
Cn.CursorLocation = adUseNone
Cn.Open
There are many users of my program so I have a table that contains each user's login name and their access rights to the various tables. I create a recordset of all users when the program is started and then select USERNAME and GRANTED_ROLE from the record set where USERNAME and PASSWORD are found. I use a "Set role 'GRANTED_ROLE' identified by 'password'" statment and Cn.Execute statement to set up the user's access rights. This is all done in a Module.
On a form, I want to call a Stored Procedure that will SELECT, INSERT and UPDATE information into another schema's tables. I am able to call and run the stored procedure when I create a new connection to the database with this code:
Dim cmd5040 As ADODB.Command
Dim conn5040 As ADODB.Connection
Dim param5040 As ADODB.Parameter
Set conn5040 = New ADODB.Connection
conn5040 = "Driver={Microsoft ODBC for Oracle};" & _
"SERVER=PSPROD; UID=XXXXXXX; PWD=XXXXXXXX"
conn5040.Open
Set cmd5040 = New ADODB.Command
With cmd5040
.ActiveConnection = conn5040
.CommandType = adCmdStoredProc
.CommandText = "S4115040_IMPORT_NEWBIDITEMSPES.S4115040_CheckTime"
.Parameters.Append .CreateParameter(, adInteger, adParamInputOutput, 5)
.Parameters.Append .CreateParameter(, adVarChar, adParamInputOutput, 400)
End With
cmd5040(0) = 0
cmd5040(1) = ""
cmd5040.CommandTimeout = 300
cmd5040.Execute
conn5040.Close
However, I get the error message "-2147217900 [Microsoft][ODCB driver for Oracle]Syntax error or access violation" when I attempt to use the same connection ('Cn') when the program first started. My code is:
Dim cmd5040 As ADODB.Command
Dim param5040 As ADODB.Parameter
Set cmd5040 = New ADODB.Command
With cmd5040
.ActiveConnection = Cn
.CommandType = adCmdStoredProc
.CommandText = "S4115040_IMPORT_NEWBIDITEMSPES.S4115040_CheckTime"
.Parameters.Append .CreateParameter(, adInteger, adParamInputOutput, 5)
.Parameters.Append .CreateParameter(, adVarChar, adParamInputOutput, 400)
End With
cmd5040(0) = 0
cmd5040(1) = ""
cmd5040.Execute
I have worked with my DBA. She has given me direct grants and direct execute privliges and I am still get the error message.
What am I doing wrong? Should I be able to use the original connection to run a stored procedure? Or must I create a second connection?
edit: on reviewing your code, I notice that the original connection Cn specifies the driver and the server name whereas the second connection conn5040 specifies the driver, server name, user and password.
Therefore, it may be that the stored procedure you are calling requires a user and password which the original cn connection does not specify
Original answer:
Make sure that the variable cn is still in scope when you try to use it. If it is declared in a module then it should be declared outside of any Sub or Function and, if other modules should be able to access it, it should be declared as Public
Option Explicit
Public cn as ADODB.Connection
Sub foo()
...
Presuming that cn is still in scope, you could examine the State property of the object which cn references to see if the Connection is still open.
If (cn.State = adStateClosed) Then
' we have a problem
...

Resources