1

Cannot insert a variable using INSERT in MS ACCESS.

the insert works great when I insert a hard-coded value such as

 dbs.Execute "INSERT INTO Flights " _
                 & "(FlightID) VALUES " _
                 & "('2');"

But fails with a variable

Private Sub MainSaveBtn_Click()
    Dim dbs As Database
    Set dbs = CurrentDb
    Dim id As Integer

    id = 20
    Debug.Print id
    dbs.Execute "INSERT INTO Flights " _
                 & "(FlightID) VALUES " _
                 & "('id');"
    dbs.Close

End Sub

*Flights table has only one Integer colum named FlightID

What am i missing here?

3
  • 1
    You are trying to insert the text 'id' into an integer column. Commented Jul 31, 2018 at 11:35
  • Are Flight and ID fields in a table or variables in your code? Commented Jul 31, 2018 at 11:35
  • id is an integer variable im trying to insert its value in the table Commented Jul 31, 2018 at 11:45

3 Answers 3

2

Do it like below :

Private Sub MainSaveBtn_Click()
    Dim dbs As Database
    Set dbs = CurrentDb
    Dim id As Integer

    id = 20
    Debug.Print id
    dbs.Execute "INSERT INTO Flights " _
                 & "(FlightID) VALUES " _
                 & "(" & CStr(id) & ");"
    dbs.Close

End Sub

Also the one worked for you is not fully correct! It should be without the single quotation as the column type is Integer like below :

 dbs.Execute "INSERT INTO Flights " _
                 & "(FlightID) VALUES " _
                 & "(2);"
Sign up to request clarification or add additional context in comments.

Comments

1

The 'id' should be a integer variable and not the string 'id'. The correct SQL statement is listed below.

dbs.Execute "INSERT INTO Flights " _
          & "(FlightID) VALUES " _
          & "(" & CStr(id) & ");"

3 Comments

Feeling stupid means you really understand and is actually a good thing. Please mark the question as answered.
Bouke. I have a problem with understanding the syntax.. How would the last statement change if i want to add an additional string variable holding a name to this INSERT?
Than it would be something like this: dbs.Execute "INSERT INTO Flights " _ & "(FlightID, FlightName) VALUES " _ & "(" & CStr(id) & ",'" & FlightNameVariable & "');" Note that FlightNameVariable should be surrounded by single quotes, because it's a string value. Basic SQL syntax is as follows: INSERT INTO TableName(Column1, Column2) VALUES (ValueColumn1, ValueColumn2)
0

It look like you are trying to insert "id" in the database. Try to concat your id in the String with the "+" symbol. Or just use a prepared statement to inject your variables in

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.