Run Insert SQL queries

ms-access-2007, sql

Solution

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

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`.

Problem

How would I run an INSERT SQL query in Microsoft Access? For Example: ``` INSERT INTO tbl_UserPurchase (ID, Name) Values (321, Joe) ```

Original source