Parameterized query in VBScript referring OracleDB - oracle

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

Related

display recordcount

I have the following, but it is not putting the count of records from the query in the MsgBox. Only the RR and the TT.
On Error Resume Next
Dim recordCount2
Set con = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
con.ConnectionString = "Provider=SQLOLEDB;Integrated Security=SSPI;Persist Security Info=False;Data Source=servername\logon;Initial Catalog=database_name"
con.Open
strQry = "SELECT * FROM smd..table_name (nolock) WHERE CAST(LastRunDate AS DATE) = CAST(GETDATE() AS DATE) AND TableNameKey in ('value1', 'value2')"
Set data = con.Open(strQry)
objRecordset.Open strQuery, adoConnection, adOpenDynamic, adLockOptimistic
recordCount2 = objRecordset.Count
MsgBox "TT " & recordCount2 & "RR"
objRS.Close: Set objRS = Nothing
con.Close: Set con = Nothing
My guess is there's an error that's occurring which is being hidden by On error resume next, and recordCount2 = objRecordset.Count is not actually succeeding. Why do you have On error resume next anyway? Delete that line or comment it out, and your problem should become obvious.
Using On Error Resume Next isn't a "magic bullet". Especially like this quote from #ansgar-wiechers
"Contrary to popular belief it doesn't magically make errors go away."
On Error Resume Next is very useful but needs to be used in the correct context. While it is active any statement that raises an error is handled silently, the statement that raised the error is skipped and the inbuilt Err object is populated with the error details for error trapping.
As others have suggested the first thing you should do when debugging these types of problems is comment out On Error Resume Next then the issues I'm about to highlight you might have found yourself.
In the example above there are a couple of lines that are likely raising errors and being skipped, these are;
Set data = con.Open(strQry)
This statement appears to want to execute the query in strQry but con.Open() is the wrong method for this, the ADODB.Connection is already open it doesn't need opening again. You likely meant (but this is a pure guess);
Set data = con.Execute(strQry)
You don't appear to use data after you try running it so I would in this situation just comment it out for now.
The next is;
objRecordset.Open strQuery, adoConnection, adOpenDynamic, adLockOptimistic
which tries to open the ADO.Recordset using strQuery which doesn't appear to defined and neither is adoConnection you likely meant (again guess work);
objRecordset.Open strQry, con, adOpenDynamic, adLockOptimistic
If this statement raises an error and is skipped the statement
recordCount2 = objRecordset.Count
will itself error because the objRecordset .State will be set to adStateClosed.
After these suggestions you should have something like;
'On Error Resume Next
Dim recordCount2, constr
Set con = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
constr = "Provider=SQLOLEDB;Integrated Security=SSPI;Persist Security Info=False;Data Source=servername\logon;Initial Catalog=database_name"
con.Open constr
strQry = "SELECT * FROM smd..table_name (nolock) WHERE CAST(LastRunDate AS DATE) = CAST(GETDATE() AS DATE) AND TableNameKey in ('value1', 'value2')"
'Set data = con.Open(strQry)
objRecordset.Open strQry, con, adOpenDynamic, adLockOptimistic
recordCount2 = objRecordset.Count
MsgBox "TT " & recordCount2 & "RR"
objRecordset.Close: Set objRecordset = Nothing
con.Close: Set con = Nothing
Avoid writing code as much as possible by writing only those lines/statements you are absolutely sure of. If you haven't seen a bit of documentation that explains why the statement x is neccessary to solve your problem, leave x off.
Before writing code, read the docs: RecordCount property:
... The cursor type of the Recordset object affects whether the number
of records can be determined. The RecordCount property will return -1
for a forward-only cursor; the actual count for a static or keyset
cursor; and either -1 or the actual count for a dynamic cursor,
depending on the data source. ...
So your plan is:
Open a connection
Get a recordset
Access its .RecordCount
The general skeleton for a VBScript contains:
Option Explicit
It does not contain the evil global OERN.
The database work specific skeleton contains:
Dim oCn : Set oCN = CreateObject("ADODB.Connection")
oCn.Open "DSN=???"
...
oCn.Close
It does not contain distracting Set x = Nothing tails.
For production scripts or test code wrt connection problems, you need to write long/complicated/tailored connection strings; for experimental code wrt small specific database features/problems/surprises a (once-for-all-puzzled-together-with-GUI-support) ODBC/DSN connection is more efficient and less error-prone.
The Recordset should be .Opened to play with the Cursor Type:
oRs.Open "SELECT AddressId FROM Person.Address", oCn, adOpenDynamic
Optional Locking left off (until you have documentary or experimental evidence that Lock Type influences .RecordCount).
If you try to run
Option Explicit
Dim oCn : Set oCN = CreateObject("ADODB.Connection")
oCn.Open "DSN=AdvWork"
Dim oRs : Set oRS = CreateObject("ADODB.Recordset")
oRs.Open "SELECT AddressId FROM Person.Address", oCn, adOpenDynamic
WScript.Echo ".RecordCount:", oRs.RecordCount
oCn.Close
you will be told: Variable is undefined: 'adOpenDynamic'. A bit of further (re)reading and your code will look like
Option Explicit
Const adOpenKeyset = 1
Dim oCn : Set oCN = CreateObject("ADODB.Connection")
oCn.Open "DSN=AdvWork"
Dim oRs : Set oRS = CreateObject("ADODB.Recordset")
oRs.Open "SELECT AddressId FROM Person.Address", oCn, adOpenKeyset
WScript.Echo ".RecordCount:", oRs.RecordCount
oCn.Close
output:
cscript 39519953.vbs
.RecordCount: 19614
and the world is a (little bit) better place.
#Brad Larson and #Ekkehard.Horner.... thanks for the guidance, i too was struggling to get the record count from a recordset using VBS and obtaining some info from the windows SYSTEMINDEX (it kept returning -1).
Setting up the Const adOpenKeyset = 1 and then adding that term to the [recordset.oen "SELECT....", oCn, adOpenKeyset] line made it work!!
you will be told: Variable is undefined: 'adOpenDynamic'. A bit of
further (re)reading and your code will look like
Option Explicit
Const adOpenKeyset = 1
Dim oCn : Set oCN = CreateObject("ADODB.Connection")
oCn.Open "DSN=AdvWork"
Dim oRs : Set oRS = CreateObject("ADODB.Recordset")
oRs.Open "SELECT AddressId FROM Person.Address", oCn, adOpenKeyset
WScript.Echo ".RecordCount:", oRs.RecordCount
oCn.Close
output: cscript 39519953.vbs .RecordCount: 19614 and the world is a
(little bit) better place.

ADO recordset not populated by ADO command execute method

I am doing some clean up to protect from SQL injection attacks happening in a older internal website that uses ASP. Here's the gist of it all in code...
Database connection is setup in a separate asp file named connect.asp
<%
on error resume next
Set DB = Server.CreateObject("ADODB.Connection")
DB.CommandTimeout = 180
DB.ConnectionTimeout = 180
connStr = "Provider=SQLOLEDB;Data Source=xxx-xxxx-xxxxxx;Initial Catalog=xxxx;Persist Security Info=True;User ID=xxxxx;Password=xxxxxxxxxxxx;"
DB.Open connStr
' Check DB connection and go to Error Handler is error exists
if DB.state=0 then
Response.Write "<p>Cannot connect to database.</p>"
TrapError Err.description
Response.end
end if
%>
This works and the db connections is opened.
I have a file named DBFunctions.asp that I use to sort of map functions to stored procedures and their parameters. I am trying to use the function below to return a ADO recordset to another asp front end page.
Function GetFacilityByFID(fid)
set rs = server.CreateObject("ADODB.Recordset")
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = DB
cmd.CommandText = "GetFacilityByFID"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter("#FID", adVarChar, adParamInput, 20)
cmd("#FID") = fid
Set rs = cmd.Execute
Set GetFacilityByFID = rs
End Function
Here is the code from the calling front end asp page, facDetail.asp
<%
Dim FID, FCBI, Error
FID = Request("FID")
FCBI = Request("FCBI")
' Check DB connection and go to Error Handler is error exists
if DB.state=0 then
Response.Write "<p>Cannot connect to database.</p>"
TrapError Err.description
Response.end
else
if FID then
Set RS = GetFacilityByFID(FID)
elseif FCBI then
Set RS = GetFacilityByFCBI(FCBI)
end if
if RS.EOF then
Response.Write "<BR><p class=alert>No record found</p>"
response.End
end if
end if
%>
The calling page is displaying that there are no records returned
but the stored procedure works when executed in SSMS.
Updated code
Here's the SQL Code for the GetFacilityByFID stored procedure.
CREATE PROCEDURE [dbo].[GetFacilityByFID]
#FID varchar(20)
AS
BEGIN
SET NOCOUNT ON;
SELECT [FAC_CBI_NBR]
,[FAC_ID]
,[FAC_TYPE]
,[FAC_SUBTYPE]
,[FAC_REGION]
,[FAC_COST_CENTER]
,[FAC_SUPPLY_CODE]
,[FAC_UPLINE]
,[FAC_SERVICE]
,[FAC_LOCATION_NAME]
,[FAC_LOCAL_ADDR1]
,[FAC_LOCAL_ADDR2]
,[FAC_LOCAL_CITY]
,[FAC_LOCAL_STATE]
,[FAC_LOCAL_ZIP]
,[FAC_MAIL_ADDR1]
,[FAC_MAIL_ADDR2]
,[FAC_MAIL_CITY]
,[FAC_MAIL_STATE]
,[FAC_MAIL_ZIP]
,[FAC_COUNTRY]
,[FAC_PHONE]
,[FAC_FAX]
,[FAC_MANAGER]
,[FAC_CONTACT]
,[FAC_CONTACT_PHONE]
,[FAC_CONTACT_EXT]
,[FAC_CONTACT_EMAIL]
,[FAC_COMMENTS]
,[FAC_CHANGED_BY]
,[FAC_LAST_UPDATE]
,[FAC_MAILOUT]
,[FAC_CONTRACTION]
,[FAC_PROPERTY_CODE]
,[FAC_ATTN_TO]
FROM [cbid].[dbo].[FACILITY]
WHERE [FAC_ID]=#FID
END
GO
Can anyone tell me what is going wrong? I have been looking at this too long and have grown frustrated with it.
Any help will be greatly appreciated!
Edit:
Current Status of issue: getting the following from the ADO provider
Error Number: -2147217904 Error Desc: Procedure or function 'GetFacilityByFID' expects parameter '#FID', which was not supplied. Error Source: Microsoft OLE DB Provider for SQL Server
You need to specify the size.
From CreateParameter Method (ADO)
If you specify a variable-length data type in the Type argument, you
must either pass a Size argument or set the
Size
property of the Parameter object before appending it to the
Parameters collection; otherwise, an error occurs.
cmd.Parameters.Append cmd.CreateParameter("#FID", adVarChar, adParamInput, Len(fid))
Before going any further, the first thing is to confirm if your stored procedure GetFacilityByFID actually returns a Recordset? Most likely it does not. If it only return a single string value, you should modify Function GetFacilityByFID(fid) to something like below:
Function GetFacilityByFID(fid)
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = DB
cmd.CommandText = "GetFacilityByFID"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Append cmd.CreateParameter("#returnVal", adVarChar, adParamOutput, 255, "")
cmd.Parameters.Append cmd.CreateParameter("#FID", adVarChar, adParamInput)
cmd("#FID") = fid
cmd.Execute
GetFacilityByFID = cmd("#returnVal")
End Function
I rewrote the function using some of the examples I found and some of LankyMart's suggestions. Thanks everyone for your help.
Here's the working code...
Function GetFacilityByFID(fid)
Set rs = server.CreateObject("ADODB.Recordset")
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = DB
cmd.CommandText = "GetFacilityByFID"
cmd.CommandType = adCmdStoredProc
cmd.CommandTimeout = 900
set prm = cmd.CreateParameter("#FID",adVarChar, adParamInput, 20, fid)
cmd.Parameters.Append prm
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
Set GetFacilityByFID = rs
On Error GoTo 0
End Function
The way you're setting the parameters looks no right, try this instead:
Dim param
Set param = cmd.CreateParameter("#FID", adVarChar, adParamInput)
cmd.Parameters.Append param
param.Value = fid
You can read more here: https://msdn.microsoft.com/pt-br/library/ms675860(v=vs.85).aspx
Hope it helps

Data is not inserted in oracle database from VB6

I want to add data in FingerData table in oracle database from VB6 . That is why , I have the following code .
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim cn As String
cn = "Provider=OraOLEDB.Oracle;Password=fingerprintdata;User ID=fingerprintdata;Data Source=10.11.201.84;Persist Security Info=True"
conn.Open cn
cmd.ActiveConnection = conn
conn.CursorLocation = adUseClient
rs.Open "FINGERDATA", conn, adOpenStatic, adLockOptimistic, adCmdTable
s = StrConv(b, vbUnicode)
rs.AddNew
rs!UserName = strName
rs!fingerdata = "123"
rs!key = "Testing 9001"
rs.Update
Set conn = Nothing
Set rs = Nothing
But the data is not inserted . What is the error ? How can I insert data in oracle database from vb6 ?
Please use this statement:
rs.Open "FINGERDATA", conn, adOpenDynamic, adLockOptimistic

VBA Recordset / Oracle and Excel Connect

I've installed tries recordset in my vba statement.
Unfortunately he accesses only the first line in my database. Who can help me?
I'm not very good in VBA it's my first porject. I hope someone can help me with my code. Thank you
Sub Testbox()
Dim conn, Rs
Dim strSQL As String
Dim auswahl As Integer
auswahl = MsgBox("Die Daten werden geladen", vbOKCancel, "Bitte auswählen")
If auswahl = 1 Then
connstring = "UID=user;PWD=passwort;DRIVER={Microsoft ODBC For Oracle};SERVER=server.WORLD;"
Set conn = New ADODB.Connection
With conn
.ConnectionString = connstring
.CursorLocation = adUseClient
.Mode = adModeRead
.Open
End With
Set Rs = CreateObject("ADODB.Recordset")
strSQL = "select * from table where logdatum =1507"
Rs.Open strSQL, conn, 3, 3
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
Rs.Close
Set Rs = Nothing
conn.Close
Set conn = Nothing
Else
Exit Sub
End If
End Sub
Unfortunately, it is not possible to print data from Recordset into worksheet like that:
Range("A2:A5000") = Rs("scanclient")
Range("B2:B500") = Rs("Sum")
Range("C2:C500") = Rs("batchclass")
You need to replace this code with the below:
Dim i As Long: i = 1
Do Until Rs.EOF
i = i + 1
Cells(i, 1) = Rs("scanclient")
Cells(i, 2) = Rs("Sum")
Cells(i, 3) = Rs("batchclass")
Call Rs.MoveNext
Loop

Search for string using VBscript and copy that column to another worksheet

I have Book1.csv and Book2.xlsx. Book1.csv has many columns with data. Each column has unique title in first ROW. I need to find column with title “Processor Time” and copy all available data in this column to column1 in Book2.xlsx using VBscript. Please help.
You can use ADO to get the column:
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Docs\;"
strcon = strcon & "Extended Properties=""Text;FMT=Delimited;HDR=Yes;IMEX=1"";"
cn.Open strcon
strSQL = "Select [Processor Time] From [Book1.csv]"
rs.Open strSQL, cn
MsgBox rs.GetString
You can use automation with Excel:
Set xl = CreateObject("Excel.Application")
You can write to Excel from a recordset with:
xl.Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
You can post back if you have problems putting the bits together.
EDIT re Comment
Try switching your code around a little:
Set xl = CreateObject("Excel.Application")
xl.Visible = True
Set objWorkbook1=xl.Workbooks.Open("C:\Docs\book2.xlsx")
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Docs\;"
strcon = strcon & "Extended Properties=""Text;FMT=Delimited;HDR=Yes;IMEX=1"";"
cn.Open strcon
strSQL = "Select [Processor Time] From [Book1.csv]"
rs.Open strSQL, cn
objWorkbook1.Worksheets("Sheet1").Cells(2, 1).CopyFromRecordset rs

Resources