Connecting Tech Pros Worldwide Forums | Help | Site Map

How to pass a parameter to an Access query from VB

Newbie
 
Join Date: Aug 2006
Posts: 2
#1: Aug 13 '06
I have a query in an Access db that prompts the user for info. (e.g. a primary key representing a company) before compiling the relevant table of results. This works fine in Access but I want to use this query from within VB.Net. But how do I, in code, pass a parameter to the Access query?

[I have noticed that .Net won't let me add this parameter query to my VB project whereas it will allow me to add other queries from the db that do not ask for a parameter.]

Expert
 
Join Date: Jul 2006
Location: Delhi India
Posts: 92
#2: Aug 23 '06

re: How to pass a parameter to an Access query from VB


here is an example that works
------------------------------

Dim cmd As New ADODB.Command
Dim rs as New ADODB.Recordset

Dim sQueryName as String
Dim lParam1 as long
Dim sParam2 as String

lParam1 = 100
sParam2 = "Miller"

sQueryName = "QueryInAccess97"

With cmd
Set .ActiveConnection = con 'con is an active ADODB.Connection
.CommandText = sQueryName
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("Param1", adInteger, adParamInput, ,
lParam1)
.Parameters.Append .CreateParameter("Param2", adVarChar, adParamInput, len(sParam2),
sParam2)
End With

rs.Open cmd, , adOpenKeyset, adLockOptimistic

DEFINITION of the query "QueryInAccess97":

PARAMETERS Param1 long, Param2 text;
SELECT FROM Table1 WHERE Table1.CustomerID =[Param1] AND Table1.Name = [Param2]

1) You must create the parameters in the same order as they are defined in
your query.(Same type and name aswell of course)
2) if you use a parameter of type 'adVarchar' its length must be passed aswell.
Expert
 
Join Date: Jul 2006
Location: Delhi India
Posts: 92
#3: Aug 23 '06

re: How to pass a parameter to an Access query from VB


Dim CMD As New ADODB.Command
Dim PRM As New ADODB.Parameter
Dim CNN as New ADODB.Connection
Dim Rec as New ADODB.Recordset
Dim Para1 as long
Para1="Hemant"
With cmd
Set .ActiveConnection = CNN ‘Select the Source of active Connection
.CommandText = "Balance" ‘Access Query Name
.CommandType = adCmdStoredProc
Set prm = .CreateParameter("Param1", adVarChar, adParamInput, Len(Para1),Para1)
.Parameters.Append prm
End With
Set Rec=cmd.Excute
Reply