简体   繁体   中英

MS Access parameterized queries VB

dbs.Execute " INSERT INTO Log " _
  & "(UserName, DateAccessed) VALUES " _
  & "(@GetLogonName, @Today);"  

GetLogonName and Today are variables but I get error "error- too few parameters, expected two". If I run the function using actual values like &"('abce', '2/2/2012') it works.

What am I doing wrong?

Thanks

Database.Execute doesn't accept query parameters, only the execution options defined in RecordsetOptionEnum .

To run a parameterized query you need to create a QueryDef object:

Dim query As QueryDef
Set query = dbs.CreateQueryDef("", "INSERT INTO LOG (UserName,DateAccessed)" & _
                                         " VALUES(@user,@time)")
query.Parameters("@user").Value = "Moo"
query.Parameters("@time").Value = Now
query.Execute

The empty string means this is a temporary QueryDef. If you enter any other name, or omit the name entirely, a new Query object will be created in the database.

If you use the same query frequently, it's a good idea to create a Query and call it by name:

Set query = dbs.QueryDefs("myQueryName")
...

QueryDef.Execute accepts the same execution parameters as Database.Execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM