问题
How would I run an INSERT SQL query in Microsoft Access?
For Example:
INSERT INTO tbl_UserPurchase (ID, Name) Values (321, Joe)
回答1:
You can build your query in Access' query designer, then while still in Design View, click "Run" on the ribbon. (Look for the red explanation point.)
If you want to do it from code, you can use the .Execute
method of either the DAO database object or the ADO CurrentProject.Connection
object.
Dim strInsert As String
strInsert = "INSERT INTO tbl_UserPurchase (ID, Name)" & vbCrLf & _
"VALUES(321, 'Joe');"
CurrentDb.Execute strInsert, dbFailOnError
However, a parameter query would be more flexible (useful for other user names, not just Joe) and prevent SQL injection.
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
And there are still other ways to skin this cat. If none of the suggestions is satisfactory, give us more details about how and where you want to run your INSERT
.
回答2:
You need to quote literals in SQL:
INSERT INTO tbl_UserPurchase (ID, Name) VALUES (321, 'Joe')
回答3:
I think name field is VarChar
(or some string value at DB) so its mean your query should be
INSERT INTO tbl_UserPurchase (ID, Name) Values(321, 'Joe');
回答4:
Try this: INSERT INTO tbl_name VALUES (1, 'xyz')
Please let me know, if that worked for you.
Good Luck
来源:https://stackoverflow.com/questions/13778917/run-insert-sql-queries