Reputation: 197
I'm trying to store the current time in my access database with the following script:
import pyodbc
import time
connStr = """
DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
DBQ=C:/Users/QPCS Registration/Documents/DB Tests/PYODBC.accdb;
"""
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
def TimeStamp():
RFID = str(input("Please tap your pass on the reader:\n"))
Current_Time = str(time.strftime("%H:%M"))
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number,Time_Tapped) VALUES('+RFID+','+Current_Time+');')
cnxn.commit()
def Close_DB_Cnxn():
cnxn.close()
TimeStamp()
Close_DB_Cnxn()
When I run it I get the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression '19:44'. (-3100) (SQLExecDirectW)")
The problem is definitely with 'Current_Time', because when I try to store the variable 'RFID' with the script shown below, it inserts into the database just fine.
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number) VALUES('+RFID+');')
I have tried changing the data type of the field 'Time_Tapped' in the table 'Time_Of_Entry' from Short Text, to Date/Time;Short Time but that has had no effect.
My machine is running on windows 7 home premium 64-bit. I have Microsoft office 2010; 32-bit I'm running python 3.3; 32-bit
Upvotes: 1
Views: 3082
Reputation: 123399
Parameterized queries are useful for both INSERT queries and SELECT queries when Date/Time values are involved. Instead of messing with date/time formats and delimiters you just pass the Date/Time value as a parameter and let the data access layer (ODBC in this case) sort it out.
The following example works for me:
from datetime import datetime, time
import pypyodbc
rfid = "GORD123" ## for testing
now = datetime.now()
currentTime = datetime(1899, 12, 30, now.hour, now.minute)
connStr = """
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
Dbq=C:/Users/Public/Database1.accdb;
"""
cnxn = pypyodbc.connect(connStr)
cursor = cnxn.cursor()
sql = """
INSERT INTO Time_Of_Entry (RFID_Number, Time_Tapped) VALUES (?, ?)
"""
parameters = (rfid, currentTime)
cursor.execute(sql, parameters)
cursor.close()
cnxn.commit()
cnxn.close()
Notes:
I used pypyodbc instead of pyodbc because I was using Python 3.4.3 and the latest pyodbc installer for Windows choked when it couldn't find Python 3.3. To get pypyodbc all I had to do was run pip install pypyodbc
.
All date/time values in Access have both a date and time component. In order for a date/time value to appear by default as time-only in Access we need to assign it the "magic" date 1899-12-30. (That's the date corresponding to CDate(0)
in Access.)
Upvotes: 1