Correct use of CurrentProject.Connection for ADODB.Connection? - ms-access

In Access VBA, I needed to use parameters for database inserts/updates so I started using a ADODB command.
The database to insert is always the current one, so I use CurrentProject.Connection.
Everything works without using conn.Open if I try to open it it will return error 3705:Operation is not allowed when the object is open.
Am I missing something important that will hit a connections limit? Can someone suggest a better way?
Dim sql As String
sql = "INSERT INTO "
sql = sql + "[table]"
sql = sql + "(field1,field2)"
sql = sql + "VALUES (#field1,#field2)"
Dim conn As ADODB.Connection
Set conn = CurrentProject.Connection
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = sql
.Parameters.Append .CreateParameter("#field1", adVarChar, adParamInput, 255, x)
.Parameters.Append .CreateParameter("#field2", adVarChar, adParamInput, 255, y)
.Execute
End With

Are you open to using DAO? you can use this:
Dim q As DAO.QueryDef
Dim strSQL As String
strSQL = "INSERT INTO table1 " & _
"(City, Province) " & _
"Values([pCity], [pProvince])"
Set q = CurrentDb.CreateQueryDef("", strSQL)
q.Parameters("pCity") = "Edmonton"
q.Parameters("pProvince") = "Alberta"
q.Execute

Related

Excel VBA MySql parameterised update 'invalid parameter type'

I am creating an interface where users can use excel to seamlessly alter an SQL database. I can retrieve data fine however when updating records I get an 'invalid parameter type'.
It works fine with just concatenating values into the query, however to prevent SQL injections I require a parameterised query. I have tried substituting in the ADO datatype with the value however this has not changed anything. I have tried unnamed parameters which just always submits a value of 16 to the database instead of the desired string value
Private Sub Worksheet_Change(ByVal Target As Range)
ID = Cells(Target.Row, 1).Value
Dim locValue As String
locValue = Cells(Target.Row, 2).Value
Dim Cm As ADODB.Command
Set Cm = New ADODB.Command
Cm.NamedParameters = True
Cm.CommandText = "UPDATE issues SET " _
& "location = #location " _
& "WHERE id = " & ID
Dim locationParameter As ADODB.Parameter
Set locationParameter = Cm.CreateParameter("#location", adVarChar, adParamInput, 255)
Cm.Parameters.Append locationParameter
locationParameter.Value = locValue
SqlConnection(Cm)
End Sub
(I am aware that ID is not yet parameterized, the issue is with the location)
Public Function SqlConnection(Cm As ADODB.Command) As ADODB.Recordset
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Server_Name = "127.0.0.1" ' Enter your server name here
Database_Name = "issues_and_outages" ' Enter your database name here
User_ID = "root" ' enter your user ID here
Password = "password" ' Enter your password here
Set Cn = New ADODB.Connection
Cn.Open "Driver={MySQL ODBC 8.0 ANSI Driver};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
Cm.CommandType = adCmdText
Cm.ActiveConnection = Cn
Set SqlConnection = Cm.Execute
End Function
The server is MySQL with an issues_and_outages table, having columns with:
id (integer, unsigned, key, auto_increment)
location (varchar(255), nullable)
When updating a cell, which should update the location column, an error of
"Run-time error '-2147217887 (80040e21)':
[MySQL][ODBC 8.0(a) Driver][mysqld-8.0.16] Invalid parameter type"
is given, with an error on the Cm.Execute line. However the database has a column of type varchar of size 255, which should be an adVarChar so I do not expect an error.
As regularly discussed and concluded with this SO answer, the ADO API for most providers/drivers does not support named parameters for non-stored procedure SQL statement. Instead use the qmark, positional parameter style.
Set Cm = New ADODB.Command
With Cm
.ActiveConnection = Cn
.CommandType = adCmdText
.CommandText = "UPDATE issues SET location = ? WHERE id = ?"
.Parameters.Append .CreateParameter("loc_param", adVarChar, adParamInput, 255, locValue)
.Parameters.Append .CreateParameter("id_param", adInteger, adParamInput,, ID)
.Execute
End With

VB6 - ADO - LIKE Paramaterized Query - Access DB

Using ADO via VB6, i'm having a hard time using the LIKE command on my access file paramaterized query.
Dim strSQL As String
strSQL = "SELECT * FROM [MY_TABLE] WHERE [MY_TEXT_COLUMN_NAME] LIKE %?%"
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DATABASE_PATH & ";Persist Security Info=False;"
conn.Open
Dim adoCommand As ADODB.Command
Set adoCommand = New ADODB.Command
With adoCommand
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = strSQL
.Prepared = True
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, 255, strMYTEXT)
Dim rs As ADODB.Recordset
Set rs = .Execute
End With
returns an empty record set
not sure the wildcards are needed here, but i just couldn't find the right way to place them.
Found it.
strSQL = "SELECT * FROM [MY_TABLE] WHERE [MY_TEXT_COLUMN_NAME] LIKE %?%"
should actually be
strSQL = "SELECT * FROM [MY_TABLE] WHERE [MY_TEXT_COLUMN_NAME] LIKE '%' + ? + '%'"
that solved it.

How to insert multiple values into a Lookup Field in an Access database via SQL?

How do you insert multiple values into a Lookup Field in an Access database using ASP?
(I've tried a few approaches, so I'm not even sure which code to show as an attempt.)
For a sample table named [Agents] with a multi-value Lookup Field named [Languages] ...
the following VBScript code represents one way to add a new Agent named "Maria" who speaks both English and Spanish
Option Explicit
Dim con, cmd, rst, newID
Const adInteger = 3
Const adVarWChar = 202
Const adParamInput = 1
Const adOpenStatic = 3
Const adLockOptimistic = 3
Set con = CreateObject("ADODB.Connection")
con.Open _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\Public\Database1.accdb"
' insert all fields *except* multi-value Lookup Field
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandText = "INSERT INTO Agents (AgentName) VALUES (?)"
cmd.Parameters.Append cmd.CreateParameter("?", adVarWChar, adParamInput, 255, "Maria")
cmd.Execute
Set cmd = Nothing
' get AutoNumber ID of newly-inserted record
Set rst = CreateObject("ADODB.Recordset")
rst.Open "SELECT ##IDENTITY", con, adOpenStatic, adLockOptimistic
newID = rst(0).Value
rst.Close
Set rst = Nothing
' insert multi-value Lookup Field values
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandText = "INSERT INTO Agents (Languages.Value) VALUES (?) WHERE AgentID=?"
cmd.Parameters.Append cmd.CreateParameter("?", adVarWChar, adParamInput, 255)
cmd.Parameters.Append cmd.CreateParameter("?", adInteger, adParamInput)
cmd.Prepared = True
cmd.Parameters(1).Value = newID
' first value
cmd.Parameters(0).Value = "English"
cmd.Execute
' second value
cmd.Parameters(0).Value = "Spanish"
cmd.Execute
Set cmd = Nothing
con.Close
Set con = Nothing
While this may answer the immediate requirements of the question, it is important to note that:
Access SQL support for manipulating Lookup Fields is incomplete and can be inconsistent from one development environment to another,
"Microsoft strongly recommends against using Access in web applications" (ref: here), and
Seasoned Access developers recommend against using Lookup Fields (ref: here) except in very specific circumstances (e.g., for integration with SharePoint).

Fill up combobox using stored procedure in vb6

How to fill up combobox during runtime using stored procedure to get values from database?
here's my code, this should be converted into stored procedure:
Private Sub ComboFill()
Set Rs = New ADODB.Recordset
Set Cmd = New ADODB.Command
With Cmd
.ActiveConnection = Conn
.CommandType = adCmdText
.CommandText = "SELECT suppliername from supplier"
Set Rs = .Execute
End With
If Not (Rs.BOF And Rs.EOF) Then
Rs.MoveFirst
End If
Do Until Rs.EOF
txtsupplier.AddItem Rs.Fields("suppliername").Value
Rs.MoveNext
Loop
End Sub
Try this (not tested):
EDIT: adjusted to return a RS, not a single value
Set Rs = New ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = Session.GetConnectionstring
cn.Open
Set cmd = New ADODB.Command
cmd.ActiveConnection = cn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = “MyStoredProcdure”
' Input param, if you need
' cmd.Parameters.Append cmd.CreateParameter(“Param1”, adInteger, adParamInput, , 614)
' Create a recordset by executing the command.
Set Rs = cmd.Execute()
Rs.MoveFirst()
Do Until Rs.EOF
txtsupplier.AddItem Rs.Fields("suppliername").Value
Rs.MoveNext
Set Rs = Nothing
Set cmd = Nothing
Set cn = Nothing

ms-access + vb6: parameterized queries without stored queries

I was wondering if in ms-access through vb6 (ADODB) i can have the security benefits of parameterized queries
Set Prm = CmdEnn.CreateParameter("pText1", adBSTR, adParamInput)
Prm.Value = pText1
Cmd.Parameters.Append Prm
without using stored procedures. So having something like:
Cmd.CommandText = "select * from ..."
Cmd.CommandType = adCmdText
instead of
Cmd.CommandText = "stored_query_name"
Cmd.CommandType = adCmdStoredProc
#KekuSemau,
Cmd.CommandText = "select * from tablename where column like #pText1"
Cmd.CommandType = adCmdText
Set Prm = CmdEnn.CreateParameter("pText1", adBSTR, adParamInput)
Prm.Value = random_variable
Cmd.Parameters.Append Prm
it worked like this, but in the end of the day, i didn't use it for other reasons. i don't recall if i had to use single quotes around it or not.