Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

vba - MS Access prepared statements

Is it possible to execute a prepared statement in MS Access on a local table in VBA like this:

UPDATE part SET part_description=? WHERE part_id=?

If so how is it done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSql As String
Set db = CurrentDb
strSql = "UPDATE Month_Totals Set item_date = [which_date]" & _
    " WHERE id = [which_id];"
Debug.Print strSql
Set qdf = db.CreateQueryDef(vbNullString, strSql)
With qdf
    .Parameters("which_date").Value = Date()
    .Parameters("which_id").Value = 1
    .Execute dbFailOnError
End With

That example used a new, unsaved QueryDef. If you have a saved parameter query, you can use it instead by substituting this line for the CreateQueryDef line:

Set qdf = db.QueryDefs("YourQueryName")

Either way, you can then refer to individual parameters by their names as I did, or by their positions in the SQL statement ... so this will work same as above:

.Parameters(0).Value = Date()
.Parameters(1).Value = 1

Additional notes:

  1. .Value is the default property for a Parameter, so including it here is not strictly required. On the other hand, it doesn't hurt to be explicit.
  2. As Gord noted below, you can use "Bang notation" with the parameter's name like !which_id, which is more concise than .Parameters("which_id")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...