VBscript call stored procedure from MySQL with output parameters [duplicate] - mysql

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.

Related

How can I use Excel to interact with MySQL and show result of an SQL query in a cell, after I enter SQL table id in another cell?

I am trying to figure out how to use Excel as an interactive front end to MySQL. It will be my first VBA experience with a database.
My scenario is I want to enter an order number into one cell, and upon completing the input, I want an SQL query to be ran, like SELECT field1, field2 FROM table WHERE order_number = ?, and then display the return result of field1 in a cell. I may use field2 in other cells.
I see there is some code here that may be useful, but I don't know where to enter that code, and how to make that code work after I enter an order number into the cell. I have already made an ODBC Driver connection to where I am able to connect to a database using Excel Database functions. I don't yet know how to use VBA do make a database connection or run interactive queries.
Can you help get me to the point where I can enter an order number in one cell, and see field1 show up in another cell, where field1 will be a value from an SQL query, like the above?
Put code on worksheet where you enter the order number. This uses a DSN created using ODBC Data Source Administrator.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ar As Variant
If Target.Address = "$B$2" Then
ar = GetOrder(Target.Value)
Range("B4") = ar(0)
Range("B5") = ar(1)
End If
End Sub
Function GetOrder(OrderNo As Long) As Variant
Const CONN = "DSN=***;UID=***;PWD=***;"
Const SQL = " SELECT Field1,Field2" & _
" FROM table1 " & _
" WHERE OrderNo = ?"
Dim dbConn As ADODB.Connection, dbCmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim param As ADODB.Parameter, n As Long
Set dbConn = New ADODB.Connection
dbConn.Open CONN
Set dbCmd = New ADODB.Command
With dbCmd
.ActiveConnection = dbConn
.CommandType = adCmdText
.CommandText = SQL
Set param = .CreateParameter("P1", adInteger, adParamInput, 0)
.Parameters.Append param
End With
Set rs = dbCmd.Execute(n, OrderNo)
If Not rs.EOF Then
GetOrder = Array(rs(0).Value, rs(1).Value)
Else
GetOrder = Array("#N/A", "#N/A")
MsgBox "Could not find " & OrderNo, vbExclamation, "Error"
End If
dbConn.Close
End Function

Arguments converted TypeError while inserting data into DB with python

Found some questions regarding this topic but none of them really solved my problem.
I'm running into some issues while trying to insert data into my SQL server, I'm pretty new in regards of Databases so my guess is that there is something wrong with how I defined the query or the values.
My code looks like this:
query = "INSERT INTO `Productos`(`IDProductos`, `ItemID`, `Nombre`, `MPN`, `Descripcion`, `URL`, `Precio`, `Departamento`, `CodigoGenerico`, `Fecha`, `Procedencia`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"
for index,row in df.iterrows():
IDProductos = '???'
ItemID = row['codigoEspecificoProducto']
Nombre = row['nombreProducto']
MPN = 'null'
Descripcion = 'null'
URL = row['urlProducto']
Precio = row ['precioProducto']
Departamento = row['categoriaProducto']
CodigoGenerico = row['codigoGenericoProducto']
Fecha = 'null'
Procedencia = 'Amazon'
values = [IDProductos,ItemID,Nombre,MPN,Descripcion,URL,Precio,Departamento,CodigoGenerico,Fecha,Procedencia]
cursor.execute(query,values)
What I'm doing is basically passing data from an excel file to my database.
Is the query I'm ussing correct? It's the one I got from copying the insert that appears in the database.
I get the TypeError: not all arguments converted during string formatting when it reaches cursor.execute(query,values)
From Excel to SQL Server.
' Set a reference to: Microsoft ActiveX Data Objects 6.1 Library
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Your_Server_Name"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub

ASP Classic Database Connection

I want to use classic ASP to open and close a connection to a SQL Server database and let it run a procedure from the database. It has no parameters.
This is the connection details in ASP, change caps to the relevant information objDBRS(0) will be your first part of data from a select statement
Set objDBConn = Server.CreateObject("ADODB.Connection")
objDBConn.Open "Provider=sqloledb;Data Source=SQLSERVERNAME;Initial Catalog=DATABASENAME; User ID=Chris;Password=PASSWORD;"
Set objDBCommand = Server.CreateObject("ADODB.Command")
objDBCommand.ActiveConnection = objDBConn
objDBCommand.CommandText = "SQLPROCEDURENAME"
objDBCommand.CommandType = adCmdStoredProc
Set objDBRS = Server.CreateObject("ADODB.RecordSet")
objDBRS.open objDBCommand,,adOpenForwardOnly
DO WHAT YOU WANT HERE
Set objDBCommand=nothing
objDBConn.Close
Set objDBConn=nothing
Here is a tried and tested approach I use over and over again.
<%
Dim cmd, conn_string, rs, data, row, rows
'Connection String if using latest version of SQL use SQL Server Native Client
'for more examples see http://www.connectionstrings.com/sql-server/
conn_string = "Provider=SQLNCLI11;Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
'No need to build ADODB.Connection the command object does it for you.
.ActiveConnection = conn_string
.CommandType = adCmdStoredProc
.CommandText = "[schema].[procedurename]"
Set rs = .Execute()
'Populate Array with rs and close and release ADODB.Recordset from memory.
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
Set rs = Nothing
End With
'Release memory closes and releases ADODB.Connection as well.
Set cmd = Nothing
'Use Array to enumerate data without overhead of ADODB.Recordset.
If IsArray(data) Then
rows = UBound(data, 2)
For row = 0 To rows
'Read data
Call Response.Write("First Field: " & data(0, row))
Next
Else
'No records
Call Response.Write("No records to display")
End If
%>

How can I get the connection string in vba from the linked tables in access 2013?

I have this linked tables on my access and I want to get the connection of it
Here is the screenshot
In my vba I tried this code but does not work because my stored procedure does not execute
Dim adocmd As New ADODB.Command
DoCmd.Maximize
adocmd.ActiveConnection = Application.CurrentProject.Connection.ConnectionString
adocmd.CommandType = adCmdStoredProc
adocmd.CommandText = "spr_DECSBillingSchedule"
adocmd.CommandTimeout = 0
On Error Resume Next
adocmd.Execute , , adExecuteNoRecords
Set adocmd = Nothing
On Error GoTo 0
How can I possibly fix this issue? thanks!
The definitions for tables are stored in a system table called MSysObjects, the connection string is in field Connect. You can access this table to get the connection string as and when you want to run the sproc (you'll need to reference a table you know is in the same database, I have front ends linked to multiple databases), though as the connection string does not change you may be better to set it to a global variable or just hard code it in (which i have fallen into the habit of doing).
NOTE: This is as per MS Access 2007, it is the only one I have installed
Below is an example of a function I use to execute a sproc, the sproc returns a value to confirm it has completed successfully, which is returned in #Ret. Hope this helps.
Function LogImportFile(strFile As String) As Long
On Error GoTo Err_Handle_LogImportFile
Set cnn = CreateObject("ADODB.Connection")
cnn.ConnectionString = "DRIVER={SQL Server};SERVER=[Server];DATABASE= _
[DatabaseName];Trusted_Connection=Yes"
' The above is for linking to a SQL Server table using a DSN less connection
' which I would highly recommend (DSN less) if you plan to distribute your
' database
cnn.Open cnn.ConnectionString
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "cmsUser.usp_LogImportFile"
cmd.CommandTimeout = 0
Set param = cmd.CreateParameter("#FileName", adVarChar, adParamInput, _
200, strFile)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("#Ret", adInteger, adParamOutput)
cmd.Parameters.Append param
cmd.Execute
LogImportFile = cmd.Parameters("#Ret")
Exit_Proc:
Set cnn = Nothing
Set cmd = Nothing
Set param = Nothing
Exit Function
Err_Handle_LogImportFile:
Msgbox "LogImportFile - " & Err.Number & " - " & Err.Description
LogImportFile = -1
GoTo Exit_Proc
End Function

MySQL / Classic ASP - Parameterized Queries

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