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.
Related
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
I am trying to retrieve records from a table in access using VBA. So far I have this simple function:
Private Function GNCN() As String
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cm As ADODB.Command
Dim strSQL As String
Dim intYD As Integer
Set cn = CurrentProject.Connection
'cn.CursorLocation = adUseClient
rs.CursorLocation = adUseClient
rs.LockType = adLockReadOnly
intYD = 16
strSQL = "SELECT DCN FROM tblDCD WHERE (DCN like '" & intYD & "*')"
Set rs = cn.Execute(strSQL)
Debug.Print rs.RecordCount
Set rs = Nothing
Set cm = Nothing
Set cn = Nothing
End Function
When I run this, I don't get any records returned.
However if I take the SQL query:
SELECT DCN FROM tblDCD WHERE (DCN like '16*')
and run this within Access' query builder, I get around 912 records returned, so I know I am able to retrieve the records and that the query itself appears to be correct.
The table is simple data which consists of string values such as (in the DCN column):
"13000"
"17001"
"16003"
Around 38000 in total so I shaln't print them all here...
Does anyone know why this will work via the query builder but not via VBA?
Thanks
Appear to be mixing DAO and ADODB. Consider:
Private Function GNCN() As String
Dim rs As DAO.Recordset
Dim strSQL As String
Dim intYD As Integer
intYD = 13
strSQL = "SELECT DCN FROM Rates WHERE DCN like '" & intYD & "*';"
Set rs = CurrentDb.OpenRecordset(strSQL)
rs.MoveLast
Debug.Print rs.RecordCount
Set rs = Nothing
End Function
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
The following code takes a parameter from a form and passes it to a stored procedure in vba. I am returning the values correctly and the stored procedure works when using debug.Print. Now I need to display the results of the stored procedure in the form "cat_percent_match". All this happens when the button is clicked. The code below does open the form, but now I need to pass the record set to it and display the results.
Any help is greatly appreciated.
Dim Cmd1 As ADODB.Command
Dim lngRecordsAffected As Long
Dim rs1 As ADODB.Recordset
Dim intRecordCount As Integer
'-----
Dim cnnTemp As ADODB.Connection
Set cnnTemp = New ADODB.Connection
cnnTemp.ConnectionString = "DRIVER=SQL Server;SERVER=***;" & _
"Trusted_Connection=No;UID=***;PWD=***;" & _
"Initial Catalog=IKB_QA;"
cnnTemp.ConnectionTimeout = 400
'Open Connection
cnnTemp.Open
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp
'---
With Cmd1
Dim localv As Integer
Dim inputv
localv = [Forms]![Start]![Selection]![cat_code]
.CommandText = "dbo.ix_spc_planogram_match_cat_percent " & inputv
.CommandType = adCmdStoredProc
Set inputv = Cmd1.CreateParameter("#deptcode", 3, 1, 10000, localv)
Cmd1.Parameters.Append inputv
Set rs1 = Nothing
Set rs1 = Cmd1.Execute
DoCmd.OpenForm "Cat_Percent_Match"
End With
End Sub
The relevant article is http://support.microsoft.com/kb/281998
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Use the ADO connection that Access uses
Set cn = CurrentProject.AccessConnection
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Customers"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
So in this particular case, you can try:
DoCmd.OpenForm "Cat_Percent_Match"
Set Forms.Cat_Percent_Match.Recordset = rs1
My requirement: To search for data in database, using VB forms and 3 text boxes.
1 TextBox, I will give Input (UserName)
1 TextBox for Location
1 TextBox for displaying output
My code is
Private Sub CommandButton3_Click()
Dim Cn As ADODB.Connection '* Connection String
Dim oCm As ADODB.Command '* Command Object
Dim sName As String
Dim rs As ADODB.Recordset
Dim uname As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set oCm = New ADODB.Command
oCm.ActiveConnection = Cn
‘Record Set
Set rs = New ADODB.Recordset
‘Select Operation
rs.Open "SampleTable", Cn, adOpenKeyset, adLockPessimistic, adCmdTable
uname = rs("UserName")
rs.Open "Select * from SampleTable where uname = '" & text1.Text & "'", ActiveConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
**'Display the Output in TextBox3**
TextBox3.Text = rs("UserName") + rs("Location")
rs.Close
Cn.Close
End Sub
I can understand the population of data is not happening so getting a RunTime error 424 at Select statement. How can I retrieve the data for the corresponding Input given?
You do not need to open the table; rs.Open "SampleTable" before searching it.
Not sure what this is for; uname = rs("UserName")
You should just run; rs.Open "Select * ... (Running the .Open on the same RS twice without closing the first is probably whats causing your error)
You should escape your input; replace$(text1.Text, "'", "''")
You should check for rs.EOF after the .open
Use & not + for concatenating strings
update
sub xxx
Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String
Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set rs = New ADODB.Recordset
sName = replace$(text1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
if (rs.eof) then
msgbox "no match"
else
TextBox3.Text = rs("UserName") & " " & rs("Location")
rs.Close
end if
set rs = nothing
Cn.Close
set cn = nothing
end sub