Parameterizing sql in asp - asp-classic

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

Related

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

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
%>

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)"

how to update entry in mysql table from asp.net?

In mysql workbench, I can type
UPDATE contact_log
SET note = 'test1'
WHERE customer = 'customer'
and it will update the customer's note.
WHen i try this in asp.net, it has no effect.
Try
conn.Open()
cmd.Connection = conn
Catch ex As Exception
End Try
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
reader = cmd.ExecuteReader()
conn.Close()
conn.Dispose()
Some facts are that the connection string is correct, I can use select and bring back data with no problem, and the request.querystring("ID") brings back the customer name.
Is there a better way to update a mysql table from asp.net, or a way that actually works?
Many problems in your code.
Do not use string concatenation to build sql commands, but
parameterized query
Do not catch exceptions and swallow them
Use the appropriate using statement to close and dispose the
connection
Of course an INSERT/UPDATE/DELETE statement requires ExecuteNonQuery
To summarize I would change your code to this
Dim cmdText = "UPDATE contact_log SET note = #note WHERE customer = #cust"
Using conn = new MySqlConnection(connString)
Using cmd = new MySqlCommand(cmdText, conn)
conn.Open()
cmd.Parameters.AddWithValue("#note",TextBox2.Text)
cmd.Parameters.AddWithValue("#cust",Request.QueryString("ID"))
Dim rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Parameterized query are very important because you avoid Sql Injections and parsing problems with string containing quotes (You will get a syntax error if the TextBox2 contains a text with a single quote)
The Using Statement will ensure that youR connection is properly closed and disposed also in case of exceptions and you avoid dangerous memory leaks and get lower usage of system resources
The exception is better handled on a upper level of your code where you could show a message to your user or write in an error log. Catching an exception and doing nothing is very bad because you will never learn what is the reason of failure in your code.
You're using the wrong command... You're WRITING to the database, not reading from it - You need to change from using a reader to an execution command....
Try this:
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
cmd.ExecuteNonQuery()
conn.Close()
conn.Dispose()

asp question ADODB.Recordset and calling a procedure

I have to make an quick update on a legacy asp page never really having done anything with classical asp want to check if this is valid.
Can I do this:
set conn = server.CreateObject("ADODB.Connection")
conn.Open ("connection string info")
Set rsIdent = server.CreateObject("ADODB.Recordset")
SQL = "EXEC procedureName #sParam = '" & someVariable & "'"
rsIdent.Open SQL, conn
iSome_ID = rsIdent.Fields("ident_value")
rsIdent.Close()
Set rsIdent = nothing
Where procedureName is a stored procedure that accepts a paramter, does some processing and returns a single record in a column called "ident_value"?
#Curtis: See How to call SQL Server stored procedures from ASP.

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