In my example code below, you can see that I have been trying to suss-out parameterized queries in ASP and MySQL.
I am doing something wrong here and would like to know what it is. In my example, you can see two queries. If I leave off the last query (under the '//////// line), this script works. As soon as I add the last query, I get the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB
status value, if available. No work was done."
I'm really not sure what I am doing wrong. I googled the error and it said something about data types but it didn't register in my empty head!
Am I declaring the parameters (.createParameter) in the right place, as I'm processing multiple queries? Do they have to be declared before all the queries?
My Code
Set connContent = Server.CreateObject("ADODB.Connection")
connContent.ConnectionString="...blah..blah..blah..."
connContent.Open
Set cmdContent = Server.CreateObject("ADODB.Command")
Set cmdContent.ActiveConnection = connContent
cmdContent.Prepared = True
Const ad_varChar = 200
Const ad_ParamInput = 1
Const ad_Integer = 3
Const ad_DBDate = 133
Const ad_DBTimeStamp = 135
theNumber = 23
theText = "Hello there!"
theDate = "2011-10-15"
SQL = " INSERT INTO testTable (integerCol) VALUES (?); "
Set newParameter = cmdContent.CreateParameter("#theNumber", ad_Integer, ad_ParamInput, 50, theNumber)
cmdContent.Parameters.Append newParameter
cmdContent.CommandText = SQL
cmdContent.Execute
' ////////////
SQL = " INSERT INTO testTable (varCharCol) VALUES (?); "
Set newParameter = cmdContent.CreateParameter("#theText", ad_varChar, ad_ParamInput, 50, theText)
cmdContent.Parameters.Append newParameter
cmdContent.CommandText = SQL
cmdContent.Execute
UPDATE:
Well I got both queries to work but I had to set another command object and active connection, shown below. Although it works, is this the right thing to do with my type of connection? Do I need to set the command object to nothing after each query then?
' ////////////
Set cmdContent = Server.CreateObject("ADODB.Command")
Set cmdContent.ActiveConnection = connContent
SQL = " INSERT INTO testTable (varCharCol) VALUES (?); "
Set newParameter = cmdContent.CreateParameter("#theText", ad_varChar, ad_ParamInput, 50, theText)
cmdContent.Parameters.Append newParameter
cmdContent.CommandText = SQL
cmdContent.Execute
I believe your problem is because both insert statements are using the same command object. Because of that, the second command will have both parameters in it and that is what I believe causes the exception you are seeing.
To fix the problem, add:
Set cmdContent = Server.CreateObject("ADODB.Command")
Set cmdContent.ActiveConnection = connContent
after your //// comment and things should start working.
Related
This question already has answers here:
Using Stored Procedure in Classical ASP .. execute and get results
(3 answers)
Closed last year.
[ EDIT 20220219 ]
Resolved using VBSCRIPT CODE below
SQL = " CALL NewCheckData(#pOld); "
cn.execute(SQL)
SQL = " SELECT #pOld; "
Set RS = cn.execute(SQL)
pOld = cInt(RS("#pOld"))
[ EDIT 20220219 ]
[EDIT]
I have a Stored Procedure on a MySQL DB.
Which simply takes the COUNT ROWS of a Parameter and returns the Value of that Parameter.
I would like to call this Stored Procedure to assign value to variable in my VBscript code.
This is MySql routine (stored procedure) tried and worked.
CREATE DEFINER=`user`#`%` PROCEDURE `NewCheckData`(OUT pOld INT (11))
BEGIN
SELECT
COUNT(*) tOld INTO pOld
FROM
`DoTable`
WHERE
DATE( myDATE ) = CURRENT_DATE;
END
VBSCRIPT CODE is as below
On Error Resume Next
Const adCmdStoredProc = 4
Const adInteger = 3
Const adVarWChar = 202
Const adParamInput = &H0001
Const adParamOutput = &H0002
Const adParamReturnValue = &H0004
Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=XXX;PORT=3306;DATABASE=XXX;USER=XXX;PASSWORD=XXX;OPTION=3;"
cn.CommandTimeout = 10000
Set cmd = CreateObject("ADODB.Command")
With cmd
Set .ActiveConnection = cn
.CommandText = "NewCheckData"
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("RETURN_VALUE", adInteger, adParamReturnValue )
.Parameters.Append .CreateParameter("#pOld", adInteger, adParamOutput, 11)
.Execute
parmval = .Parameters(0).Value
End With
cn.Close()
Set cn = Nothing
If Err.Number <> 0 Then
WScript.Echo "Error in : " & Err.Description
Err.Clear
End If
On Error GoTo 0
Error or messagebox
Error or messagebox
Any suggestion, please.
[OLD QUESTION]
I am working with VBSCRIPT and using stored procedure MySQL.
I have to get the value of stored procedure out parameter.
This is MySql routine (stored procedure) tried and worked
CREATE DEFINER=`user`#`%` PROCEDURE `CheckData`(OUT pOld INT (11))
BEGIN
SELECT
COUNT(*) tOld INTO pOld
FROM
`DoTable`
WHERE
DATE( myDATE ) = CURRENT_DATE;
END
VBSCRIPT CODE is as below
Set cn = CreateObject("ADODB.Connection")
cn.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=XXX;PORT=3306;DATABASE=XXX;USER=XXX;PASSWORD=XXX;OPTION=3;"
cn.CommandTimeout = 1000
Set objCommandSec = CreateObject("ADODB.Command")
objCommandSec.ActiveConnection = cn
objCommandSec.CommandType = 4
objCommandSec.CommandText = "CheckData"
objCommandSec.Parameters.Refresh
objCommandSec.Parameters.append objCommandSec.createParameter("#pOld", adInteger, adParamReturnValue) <<< error line
objCommandSec.execute , , adExecuteNoRecords
pOld = objCommandSec.Parameters("#pOld").value
MsgBox(pOld)
cn.Close()
Set cn = Nothing
Error or messagebox line 15
Error 'Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another'
Any suggestion, please.
Edit: I failed to consider and mention that the below code example is accessing a MS-SQL DB. The behavior could therfor be different.
I don't use .VBS much anymore, but as I believe you are using the "Windows Script Host" environment I don't think it will make much difference. In the past I have done essentially the same thing as you demonstrate above many times with WSH & .JS. I also always ran into problems when I explicitly added the parameter definitions. I have since learned that for me the .refresh() is completely sufficient. I therefore leave .createParameter out now and simply give the named parameters the needed values as such:
var jsADO = {};
jsADO.objConn = new ActiveXObject("ADODB.Connection");
jsADO.objConn.Open("Provider=SQLOLEDB.1;...");
jsADO.cmd_insertShare = new ActiveXObject("ADODB.Command");
var cmd = jsADO.cmd_insertShare;
cmd.ActiveConnection = jsADO.objConn;
cmd.CommandType = adCmdStoredProc; // 4
cmd.CommandText = "usp_insertShare";
cmd.Prepared = true;
cmd.NamedParameters = true;
cmd.Parameters.Refresh()
...
var sqlRec;
var cmd = jsADO.cmd_insertShare;
cmd.Parameters("#p_Server") = "myServer";
cmd.Parameters("#p_Name") = "myShare";
cmd.Parameters("#p_Description") = "myShare Desc";
cmd.Parameters("#p_LocalPath") = "sharePath";
sqlRec = cmd.Execute(null, null, 0);
The syntax is indeed different, but I hope the gist is clear.
In summary, I think you've got it, just try leaving the .createParameter function out and only setting the named parameter values.
I'm facing a problem when I want to update data from local database to server data, replacing everything that has been modified at local database. I know it might be simple but I got no idea about this, so any help will be appreciate.
In my situation, I want to use a button to upload all modified data to
the server database. Now I'm just using 2 databases at same server to do
testing.
Private Sub btnUp_Click(sender As System.Object, e As System.EventArgs) Handles btnUp.Click
localconn.ConnectionString = lctext
serverconn.ConnectionString = sctext
Try
localconn.Open()
serverconn.Open()
Dim localcmd As New OdbcCommand("select a.acc_id as localid, a.acc_brcid, a.smartcardid, a.acc_created, a.acc_modified as localmodified, b.acd_firstname, b.acd_ic, b.acd_oldic, b.acd_race, b.acd_dob, b.acd_rescity, b.acd_resaddr1, b.acd_telmobile, b.acd_email, b.acd_telwork, b.acd_modified, b.acd_accid from nsk_account a inner join nsk_accountdetail b on a.acc_id = b.acd_accid", localconn)
Dim servercmd As New OdbcCommand("select c.acc_id, c.acc_brcid, a.smartcardid, c.acc_created, c.acc_modified, d.acd_firstname, d.acd_ic, d.acd_oldic, d.acd_race, d.acd_dob, d.acd_rescity, d.acd_resaddr1, d.acd_telmobile, d.acd_email, d.acd_telwork, d.acd_modified, d.acd_accid from nsk_account c inner join nsk_accountdetail d on c.acc_id = d.acd_accid", serverconn)
localcmd.CommandType = CommandType.Text
Dim rdr As OdbcDataReader = localcmd.ExecuteReader()
Dim thedatatable As DataTable = rdr.GetSchemaTable()
'localcmd.Parameters.Add("#localid", OdbcType.Int, "a.acc_id")
'localcmd.Parameters.Add("#localmodified", OdbcType.DateTime, "b.acd_modified")
Dim localid As String
Dim localmodi As String
localcmd.Parameters.AddWithValue("localid", localid)
localcmd.Parameters.AddWithValue("localmodified", localmodi)
For Each localid In thedatatable.Rows
Dim calldata As New OdbcCommand("SELECT acc_modified from nsk_account where acc_id ='" + localid + "'", serverconn)
Dim reader As OdbcDataReader = calldata.ExecuteReader
txtSDate.Text = reader("acc_modified").ToString
If localmodi <= txtSDate.Text Then
'do nothing, proceed to next data
Else
Dim ACCoverwrite As New OdbcCommand("Update nsk_account SET smartcardid = #mykad, acc_created = #created, acc_modified = #modify WHERE acc_id ='" + localid + "'", serverconn)
Dim DEToverwrite As New OdbcCommand("Update nsk_accountdetail SET acd_firstname = #name, acd_ic = #newic, acd_oldic = #oldic, acd_race = #race, acd_dob = #dob, acd_rescity = #city, acd_resaddr1 = #address, acd_telmobile = #phone, acd_email = #email, acd_telwork = #language, acd_modified = #detmodify WHERE acd_accid ='" + localid + "'", serverconn)
ACCoverwrite.ExecuteNonQuery()
DEToverwrite.ExecuteNonQuery()
End If
Next
MessageBox.Show("Upload success", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Finally
localconn.Close()
serverconn.Close()
End Try
End Sub
any comment or suggestion will be appreciate.
I hope you mean table by table. I didn't read your code much but you got the idea - you need 2 connections but here where there are 2 distinct ways of doing it.
Way #1 - you can use when amounts of data (how to say it better? - not huge). You can load a DataTable object with data from server and update changed records. You can use DataAdapter and issue CommitChanges - all changed/new rows will be written to server.
NOTE: you need a mechanism that will reliably able to tell which rows are new and modified on your local DB. Are you OK if your PK in local DB will be different than on the server? You need to answer these questions. May be you need a special mechanism for PK locally. For example, add rows using negative PK integers, which will tell you that these rows are new. And use "ModifiedDate", which together with PK will tell if the row needs updating.
Way #2 - use anytime, even with larger amount of data. Take a local row and examine it. If it is new - insert, if it is existing and "DateModified" changed - do update. There are variations of how to do it. You can use SQL MERGE statement, etc.
But these are two major ways - direct row insert/update and disconnected update/mass commit.
Also, you can do it in bulk, using a transaction - update some rows-commit, and start new transaction. This will help if the application being used as you updating it.
I hope these ideas help. If you do what you do, where you have
For Each localid In thedatatable.Rows
I am not sure what localid is. It should be
' prepare command before loop
sql = "Select * From Table where ID = #1"
' you will create parameter for #1 with value coming from
' row("ID")
Dim cmd As New .....
cmd.Parameters.Add(. . . . )
For Each row As DataRow In thedatatable.Rows
cmd.Parameters(0).Value = row("ID") ' prepare command upfront and only change the value
using reader as IDataReader = cmd.ExecuteReader(. . . . )
If Not reader.Read() Then
' This row is not found in DB - do appropriate action
Continue For
Else
' here check if the date matches and issue update
' Better yet - fill some object
End if
end using
' if you fill object with data from your row -here you can verify if
' update needed and issue it
. . . . . .
Next
I have a CSV file with no header output by a process I do not control:
FOO,<auto>,12345678,8005882300, ,2
FOO,<auto>,23456789,2128675309, ,2
FOO,<auto>,34567890,3125577203, ,2
FOO,<auto>,45678901,9198423089, ,2
I'm trying to access it using Classic ASP with ADO then print out the phone number using this code:
stmt = "SELECT * FROM baz.txt"
connectstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=I:;Extended Properties='Text;HDR=No;FMT=Delimited'"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connectstring
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open stmt, conn, adLockOptimistic, , adCmdText
If Not rs.eof Then
Data=rs.GetRows()
End If
for r = 0 to UBound(Data,2)
response.write(Data(3,r) & "<br>")
next
Even though I have the HDR flag set to No the result set never includes the first row:
2128675309
3125577203
9198423089
What am I doing wrong that it appears the first row is still being skipped?
I wanted to post the answer to my own question in case someone else runs into a similar situation in the future.
For the purposes of the post I had oversimplified my code, and in so doing I had removed the thing that was making it break. The code was actually contained within a loop to iterate through several files in several subfolders:
path = "I:"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set dirFolders = objFSO.GetFolder(path).SubFolders
For Each subFolder in dirFolders
Set dirFiles = objFSO.GetFolder(subFolder).Files
For Each bar in dirFiles
stmt = "SELECT * FROM " & bar
connectstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& path &";Extended Properties='Text;HDR=No;FMT=Delimited'"
[...]
In practice, this is what was actually getting passed to ADO:
stmt = "SELECT * FROM I:\20140509\baz.txt"
connectstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=I:;Extended Properties='text;HDR=No;FMT=CSVDelimited'"
Having the full path included in stmt and an incomplete path in connectstring caused the HDR flag to be ignored. It would have been nice if ADO had broken a little less subtly when I fed that to it, but it is what it is.
Corrected code:
For Each path in dirFolders
Set dirFiles = objFSO.GetFolder(path).Files
For Each bar in dirFiles
stmt = "SELECT * FROM " & objFSO.GetFileName(bar)
connectstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& path &";Extended Properties='Text;HDR=No;FMT=Delimited'"
Ultimately, it's a reminder that chucking a couple of response.write statements at puzzling code is a Good Idea, and when it doesn't work like you expect, to strip it down to brass tacks to make sure you're looking in the right place.
I am getting the following error in my classic asp application:
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
Transaction cannot have multiple recordsets with this cursor type.
Change the cursor type, commit the transaction, or close one of the
recordsets.
i am working on migrating the code from Oracle to SQL Server 2008, and this is an issue that i keep seeing here and there, all through out the application.
can't seem to find any fixes for it.
this particular case in this block of code: (i changed the selects to make them shorter)
Set MyConn = Server.CreateObject("ADODB.Connection")
Call OpenORPSConnect(MyConn)
ql = "Select username from mytable"
set rs = MyConn.Execute(sql)
if not rs.EOF then username = rs(0)
if username = "" then username = theUser
rs.close()
set rs = nothing
MyConn.BeginTrans()
sql = "Select someReport from MyTable"
set rs = MyConn.Execute(sql)
do while not rs.EOF
TIMESTAMP = rs("TIMESTAMP")
rev = rs("REV")
select case whatChange
case "Target date"
sql = "Insert into " & caJustTable & _
" (TEXT, TIMESTAMP, CURRENTFLAG)" & _
" Values ( Text& "','" & COPY_TS & "', 'Y')""
MyConn.Execute(sql)
end select
sql = "update table, set this to that"
MyConn.Execute(sql) <-------- error happens here sometimes....
end if
rs.movenext
loop
rs.close()
set rs = nothing
Since this was answered in the comments I wanted to turn it into a better answer
Your problem seems to be the MyConn.BeginTrans() has no MyConn.CommitTrans() or MyConn.RollbackTrans() after the Insert Statement in your select case; therefore, an error is thrown when you try to update the data. If you commit or Rollback after that insert execute then your next execute should work just fine. The fact that the MyConn.BeginTrans() is before a simple select statement you might consider moving it after the select.
I would do something like this (if you want to use transactions):
'MyConn.BeginTrans()
sql = "Select someReport from MyTable"
set rs = MyConn.Execute(sql)
do while not rs.EOF
TIMESTAMP = rs("TIMESTAMP")
rev = rs("REV")
select case whatChange
case "Target date"
MyConn.BeginTrans()
sql = "Insert into " & caJustTable & _
" (TEXT, TIMESTAMP, CURRENTFLAG)" & _
" Values ( Text& "','" & COPY_TS & "', 'Y')""
MyConn.Execute(sql)
MyConn.CommitTrans() 'You'll want to validate your data inserts properly before committing
end select
MyConn.BeginTrans()
sql = "update table, set this to that"
MyConn.Execute(sql) <-------- error happens here sometimes....
MyConn.CommitTrans()'You'll want to validate your data inserts properly before committing
end if
rs.movenext
loop
rs.close()
set rs = nothing
Transactions are generally used for inserting/updating or deleting data. Since you commented you don't know why the BeginTrans() statement is there then yes you could remove it altogether but I would recommend reading up on transactions and making sure you don't need it after your insert and update statements which occur later in the code.
Here is a reference for SQL transactions:
http://www.firstsql.com/tutor5.htm
I think MyConn may need to be closed at the end. Is this something you can try??
You already have an open recordset on the connection, so I think the problem is that your database does not support additional actions on the same connection until the recordset is closed. As a fix, I would recommend one of three options:
Use a second connection (on which you run the transaction) to run the sql statements that update the table.
Collect all statements into a list while you loop through the recordset, close the recordset, and then run the statements (using the same connection).
Or pull the data into a data table and loop through that rather than an open recordset.
In an absolute emergency, I am trying to go through my website and add parameterized queries. I'm a newbie and have only just learnt about them.
My problem is, I only know a very little about connection types and all of the examples I'm seeing are using another methods of connection, which is confusing me. I don't particularly want to change the way I connect to my DB, as it's on lots of pages, I just want to update my queries to be safer.
This is how I have been connecting to my DB:
Set connContent = Server.CreateObject("ADODB.Connection")
connContent.ConnectionString = "...blah...blah...blah..."
connContent.Open
and this is the SQL bit with parameters:
username = Trim(Request("username"))
connContent.Prepared = True
Const ad_nVarChar = 202
Const ad_ParamInput = 1
SQL = " SELECT * FROM users WHERE (username=?) ; "
Set newParameter = connContent.CreateParameter("#username", ad_nVarChar, adParamInput, 20, username)
connContent.Parameters.Append newParameter
Set rs = connContent.Execute(SQL)
If NOT rs.EOF Then
' Do something...
End If
rs.Close
It's obviously not working but I need to know if I can actually achieve this using the connection I have or am I missing something altogether that's stopping it from working?
Before I go forth and spend the next 2 days debugging something I'm unfamiliar with, I would like to know I'm at least on the right track...
The code in your second snippet is correct, but should be applied to a new ADODB.Command object, not to the Connection object:
username = Trim(Request("username"))
'-----Added this-----
Dim cmdContent
Set cmdContent = Server.CreateObject("ADODB.Command")
' Use this line to associate the Command with your previously opened connection
Set cmdContent.ActiveConnection = connContent
'--------------------
cmdContent.Prepared = True
Const ad_nVarChar = 202
Const ad_ParamInput = 1
SQL = " SELECT * FROM users WHERE (username=?) ; "
Set newParameter = cmdContent.CreateParameter("#username", ad_nVarChar, ad_ParamInput, 20, username)
cmdContent.Parameters.Append newParameter
cmdContent.CommandText = SQL
Set rs = cmdContent.Execute
If NOT rs.EOF Then
' Do something...
End If
rs.Close
By the way, there was a typo with the spelling of adParamInput instead of ad_ParamInput (corrected in my example).