Joseph Webber
Joseph Webber

Reputation: 2173

Insert date into Access database gives syntax error

Trying to insert the current date into my Access database throws a syntax error for the INSERT INTO statement.

My database contains a field named Day which has the data type Date/Time.

My insert statement is:

Try
    dbConnection.Open()
    sqlString = "INSERT INTO table1 (Day) VALUES (@Day)"
    dbCommand.CommandText = sqlString
    dbCommand.Parameters.AddWithValue("@Day", FormatDateTime(Now, 2))
    dbCommand.ExecuteNonQuery()
Finally
    dbConnection.Close()
End Try

When I do Response.Write(FormatDateTime(Now, 2)) it displays 10/29/2013, which should be an acceptable record.

Doing these also throw a syntax error in the INSERT INTO statement:

Try
    dbConnection.Open()
    sqlString = "INSERT INTO table1 (Day) VALUES (Now())"
    dbCommand.CommandText = sqlString
    dbCommand.ExecuteNonQuery()
Finally
    dbConnection.Close()
End Try

Try
    dbConnection.Open()
    sqlString = "INSERT INTO table1 (Day) VALUES (#" & FormatDateTime(Now, 2) & "#)"
    dbCommand.CommandText = sqlString
    dbCommand.ExecuteNonQuery()
Finally
    dbConnection.Close()
End Try

Are the dates not in an acceptable format for the field?

Upvotes: 1

Views: 329

Answers (1)

HansUp
HansUp

Reputation: 97101

Day is a reserved word. Enclose that name in square brackets to avoid confusing the db engine.

sqlString = "INSERT INTO table1 ([Day]) VALUES (Now())"

Upvotes: 1

Related Questions