如何在Microsoft Access中运行INSERT SQL查询?

例如:

INSERT INTO tbl_UserPurchase (ID, Name) Values (321, Joe)

最佳答案

您可以在Access的查询设计器中构建查询,然后仍在“设计视图”中,单击功能区上的“运行”。 (寻找红色的解释点。)

如果要通过代码执行此操作,则可以使用DAO数据库对象或ADO .Execute对象的CurrentProject.Connection方法。



Dim strInsert As String
strInsert = "INSERT INTO tbl_UserPurchase (ID, Name)" & vbCrLf & _
    "VALUES(321, 'Joe');"
CurrentDb.Execute strInsert, dbFailOnError


但是,参数查询将更加灵活(对其他用户名有用,而不仅仅是Joe),并且可以防止SQL注入。

Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim strInsert As String

strInsert = "INSERT INTO tbl_UserPurchase (ID, Name)" & vbCrLf & _
    "VALUES (321, [which_user]);"
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
' you could read the parameter value from a text box on a form,
' but this example will just hard code Joe
qdf.Parameters("[which_user]").value = "Joe"
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing


而且还有其他方法可以给这只猫蒙皮。如果所有建议都不令人满意,请向我们提供有关如何运行INSERT的详细信息。

10-05 20:28