我尝试使用以下脚本将当前时间存储在我的访问数据库中:
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()
当我运行它时,出现以下错误:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression '19:44'. (-3100) (SQLExecDirectW)")
问题肯定出在“Current_Time”上,因为当我尝试使用下面所示的脚本存储变量“RFID”时,它会很好地插入到数据库中。
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number) VALUES('+RFID+');')
我尝试将“Time_Of_Entry”表中“Time_Tapped”字段的数据类型从“短文本”更改为“日期/时间;短时间”,但这没有效果。
我的机器运行的是 Windows 7 Home Premium 64 位。我有 Microsoft Office 2010; 32位我正在运行python 3.3; 32位
最佳答案
当涉及日期/时间值时,参数化查询对于 INSERT 查询和 SELECT 查询都很有用。您只需将日期/时间值作为参数传递,然后让数据访问层(在本例中为 ODBC)对其进行排序,而不用弄乱日期/时间格式和分隔符。
以下示例适用于我:
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()
注释:
我用了 pypyodbc而不是 pyodbc,因为我使用的是 Python 3.4.3,而最新的 Windows pyodbc 安装程序在找不到 Python 3.3 时卡住了。要获取 pypyodbc,我所要做的就是运行
pip install pypyodbc
。Access 中的所有日期/时间值都包含日期和时间部分。为了使日期/时间值在 Access 中默认显示为仅时间,我们需要为其分配“神奇”日期 1899-12-30。 (这是与 Access 中的
CDate(0)
相对应的日期。)
关于python - 使用 python odbc 将时间插入 MS Access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28751539/