我尝试使用以下脚本将当前时间存储在我的访问数据库中:
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_Tapped'在表格中,Time_Of_Entry'从短文本到日期/时间;短时间但没有效果。
我的机器在Windows 7家庭高级版64位上运行。我有Microsoft Office 2010; 32位我正在运行python 3.3; 32位
答案 0 :(得分:1)
当涉及日期/时间值时,参数化查询对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中,我们需要为其分配" magic"日期1899-12-30。 (这是与Access中的CDate(0)
对应的日期。)