Parameterized query in Classic Asp - vbscript

My db access code is like following:
set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1 = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn //connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
set prm = cmd1.CreateParameter("#prm", 200, 1,200 , "development")
cmd1.Parameters.Append prm
set recordset = cmd1.Execute
But there is no db hit going. Please help with this. I am using sql server 2005.
Thanks.

In my code, this is how I get a recordset from a command:
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
cmd.ActiveConnection = Conn //connection object already created
cmd.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
set prm = cmd.CreateParameter("#prm", 200, 1, 200, "development")
cmd.Parameters.Append prm
' Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
Hope it helps

I like using Parameters.Refresh, i.e.
set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1 = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn ' connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
cmd1.Prepared = True ' only needed if u plan to reuse this command often
cmd1.Parameters.Refresh
cmd1.Parameters(0).Value = "development"
set recordset = cmd1.Execute

Looks like you aren't referencing your named parameter correctly in your query.
Try replacing:
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
with:
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = #prm"
and see if that helps.

If you have a complex criteria using parameters here is an example I had to create based on my requirements
declare #loc smallint = ? , #dt1 date = ? SET #loc = ISNULL(#loc, 999)
SELECT m.* , c.*
FROM Costs c INNER JOIN MbrData m ON c.SN = m.SN and c.startDT = m.startDT
WHERE (m.LocationID = #loc OR #loc = 999) AND (MonthYear = #dt1 OR #dt1 IS NULL)
ORDER BY m.LocationID
then in your asp
cmd.CommandText = strSQL ' the string above
cmd.CommandType = 1 ' adCmdText
cmd.Parameters.Append cmd.CreateParameter("#loc",2,1) 'adSmallInt=2, adParamInput=1
cmd.Parameters("#loc") = rptlocation ' scrubbed location ID
cmd.Parameters.Append cmd.CreateParameter("#dt1",7,1) 'adDate=7, adParamInput=1
cmd.Parameters("#dt1") = scrubbed formatted date
set rst = cmd.Execute

Try leaving off the parameter name:
set prm = cmd1.CreateParameter(, 200, 1,200 , "development")

Related

Parameterized query in VBScript referring OracleDB

I have a parameterized query which is giving
"ORA-01008: not all variables bound" error.
Dim Conn
Dim Cmd
Dim RS
Dim strID
Dim param
strID = Request.QueryString("id")
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConnect
Set Cmd = Server.CreateObject("ADODB.Command")
Cmd.CommandText = "SELECT column_name FROM table WHERE (id = :id)"
Set param = Cmd.CreateParameter("id", adVarChar , adParamInput ,50 , strID)
Cmd.Parameters.Append param
Cmd.CommandType = adCmdText
Set Cmd.ActiveConnection = Conn
Set RS = Cmd.Execute()
I'm trying to modify in syntax in several ways, then it is giving
ORA-00936: missing expression
Please help me to get out of this. For your information, there is no problem with connection as i am able to connect with normal query.
a few things to check:
1) try hard coding a value for strID, so instead of:
strID = Request.QueryString("id")
try
strID = 100
2) double check your column definitions and make sure you're selecting from a varchar(50) field
3) make sure you have adovbs.inc referenced on your page for the ADO constants definitions
Thanks #Lankymart, luckily i got solution for this as below. It is working fine for me and sorry for the delay in posting the answer, my issue resolved 2 hours ago.
Dim Conn
Dim Cmd
Dim RS
Dim strID
Dim param
strID = Request.QueryString("id")
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open strConnect
Set Cmd = Server.CreateObject("ADODB.Command")
With Cmd
.CommandText = "SELECT column_name FROM table WHERE id = ?"
.Parameters.Append .CreateParameter(,200, 1 ,50 ,strID)
Set .ActiveConnection = Conn
End With
Set RS = Cmd.Execute()

Oracle and ADO Query from Excel returns no results

I am having trouble running a query in Excel 2010 VBA code using Oracle OraOLEDB.Oracle Provider.
Certain queries work fine and return results, while others return no results...
I connect as such:
Set DBConnection = New ADODB.Connection
DBConnection.Provider = "OraOLEDB.Oracle"
DBConnection.CursorLocation = adUseClient
DBConnection.ConnectionString = "Data Source=" & TNSName & ";User Id=" & OraUserName & ";Password=" & OraPassWord & ";"
DBConnection.Open
I then try to query:
command2.ActiveConnection = DBConnection
command2.CommandText = "SELECT COL1,COL2,COL3 FROM table(MySchema.MyPackage.MyFunction('Param1'))"
command2.CommandType = adCmdText
Set QueryRecordSet = New ADODB.Recordset
QueryRecordSet.LockType = adLockReadOnly
QueryRecordSet.CursorType = adOpenDynamic
QueryRecordSet.Open command2
command2.Execute
and I get nothing...any ideas?
If I run a simple query like
select * From my_table
it works fine...it seems joins or other more complex queries don't compile??
Additionally, selecting from views does not work.
select * from my_view
Returns nothing
I'm putting this as an answer only because comment formatting doesn't allow me to add code.
Does the stored procedure work if you run it separately via the command object?
command2.CommandText = "MySchema.MyPackage.MyFunction"
command2.CommandType = adCmdStoredProc
command2.Parameters.Refresh
command2.Parameters.Item(1).Value = "Param1"
command2.Execute
Debug.Print command2.Parameters.Item(0).Value
I am not sure this is what you are looking for. I was looking for another answer and I know this works for me.
Set cmdSum = New adodb.Command
With cmdSum
Set .ActiveConnection = oCon
.Properties("PLSQLRSet") = True
.CommandText = "{CALL StoredProc(?,?)}"
.CommandType = adCmdText
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, 10, Format(CDate(sTerm), "mm/dd/yyyy"))
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, 10, Format(CDate(sEff), "mm/dd/yyyy"))
End With
Set Rs = cmdSum.Execute()
For c = 0 To Rs.Fields.Count - 1
Wk.Cells(3, c + 1) = Rs.Fields(c).Name
Next c
I ended up here after an Excel ADO query to Oracle would not work.
Although it states in the questions' comments that you can use ODBC to work-around this, it took me a while to figure out how to get the ODBC connection string working.
Here is an ODBC connection to Oracle that I got working.
dbConn = "ODBC;Provider=OraOLEDB.Oracle;" & _
"Data Source=odbc_connection_name;" & _
"User Id=user_id;" & _
"Password=user_pwd;" & _
"DBQ=tns_name;"
tns_name is what you named your connection within the tnsnames.ora file.
odbc_connection_name is what you named your odbc connection.
Then you can just use this to connect to Oracle using ADO like normal:
cn.Open dbConn
cn.CommandTimeout = 1000
rs.Open sql, cn
Note I also had to increase the CommandTimeout property, as ODBC's default timeout is relatively short.

214721900 error during run time

What is wrong in this code:
Dim con As ADODB.Connection
Dim rec As ADODB.Recordset
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Dim count As Integer
con.Open "Provider=MSDAORA.1;Password=****;User ID=system;Persist Security Info=False"
con.CursorLocation = adUseClient
rec.Open "select count(*) as c from login_hisab where username = " & Text1.Text & " and password = " & Text2.Text & "", con, adOpenDynamic, adLockOptimistic
count = rec.Fields("c")
If count = 0 Then
MsgBox "Invalid USERNAME or PASSWORD"
End If
You probably have to put your sql values inside single quotes:
where username = '" & Text1.Text & "' and password = '" & Text2.Text & "'"
Try using a parameterized query like this (air code). Means you don't have to worry about passwords containing ' or ", you don't have to worry about SQL Injection, etc.
dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.CommandType = adCmdText
cmd.CommandTimeout = 30
cmd.CommandText = "select count(*) as c from login_hisab where username = ? and password = ?"
cmd.Parameters.Append cmd.CreateParameter("userid", adVarChar, _
adParamInput, Len(Text1.Text), Text1.Text)
cmd.Parameters.Append cmd.CreateParameter("pwd", adVarChar, _
adParamInput, Len(Text2.Text), Text2.Text)
cmd.ActiveConnection = con
Set rec = cmd.Execute()
count = rec.Fields("c")
If count = 0 Then
MsgBox "Invalid USERNAME or PASSWORD"
End If

How to add picture into database?

I have created a table mypics that contains one column of BLOB datatype.
Now I need to implement a vb6 code to Select/Insert/Update data in this table, but I don`t know how to deal with the BLOB column...
SQL> desc mypics
Name Null? Type
PID NOT NULL NUMBER(38)
PNAME CHAR(10)
IMAGE BLOB
Please help
Here is some example code to get you started. Assume a table named tblImages with 3 fields.
Field Data Type Size
Picture Image
ID Int 4
To add an image from a file on disk to the database
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.LoadFromFile strFileName
strSQL = "SELECT ID, Picture FROM tblImages"
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
rs.AddNew
rs.Fields("ID").Value = ID
rs.Fields("Picture").Value = strStream.Read
rs.Update
rs.Close
Set rs = Nothing
To extract the file from database to a disk file :
strSQL = "SELECT Picture FROM tblImages WHERE ID = " & ID
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Source = strSQL
.Open
End With
If Not (rs.BOF And rs.EOF) Then
Set strStream = New ADODB.Stream
strStream.Type = adTypeBinary
strStream.Open
strStream.Write rs!Picture
strStream.SaveToFile TempPath, adSaveCreateOverWrite
strStream.Close
Set strStream = Nothing
End If
rs.Close
Set rs = Nothing
I hope this helps.

updating the table using recordset

I have a recordset rcdDNE. I want to update my reclamation by making some conditions with my existing recordset. But my table is not updating. Can you guys tell me where I am doing wrong?
Dim lngRecCount As Long
frmDNELoad.lblStatus.Caption = "Updating records in Reclamation Table..."
frmDNELoad.Refresh
CqDate = Format(Date, "dd/MM/yyyy")
Set rcdreclamation = New ADODB.Recordset
With rcdreclamation
.ActiveConnection = objConn
.Source = "SELECT * FROM T_DATA_reclamation"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
rcdDNE.MoveFirst
Do Until rcdDNE.EOF
With cmdDNEFRC
.ActiveConnection = objConn
.CommandText = "update t_data_reclamation set ClaimStatus = 'C',DateClosed = 'CqDate', Audit_LastUpdated = 'CqDate', Audit_UserAdded = 'SYSTEM' where RTProvided = '" & rcdDNE("AccountNbr") & "'"
.CommandType = adCmdText
End With
rcdDNE.MoveNext
Loop
Unless its something you forgot to put in your sample code, You are missing a call to the Execute function inside your Command object's with block.
With cmdDNEFRC
.ActiveConnection = objConn
.CommandText = "update t_data_reclamation set ClaimStatus = 'C',DateClosed = 'CqDate', Audit_LastUpdated = 'CqDate', Audit_UserAdded = 'SYSTEM' where RTProvided = '" & rcdDNE("AccountNbr") & "'"
.CommandType = adCmdText
.Execute 'dont forget execution
End With
Also when writing data to the table, using Connection objects BeginTrans and CommitTrans function is recommended, just in case something has to go wrong when writing the data you don't end up with data inconsistencies.

Resources