【问题标题】:Inserting time into MS Access with python odbc使用 python odbc 将时间插入 MS Access
【发布时间】:2015-02-26 19:53:48
【问题描述】:

我正在尝试使用以下脚本将当前时间存储在我的访问数据库中:

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 家庭高级版 64 位上运行。我有 Microsoft Office 2010; 32位我正在运行python 3.3; 32 位

【问题讨论】:

标签: python odbc ms-access-2010 pyodbc


【解决方案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()

注意事项:

  1. 我使用了pypyodbc 而不是 pyodbc,因为我使用的是 Python 3.4.3,而最新的适用于 Windows 的 pyodbc 安装程序在找不到 Python 3.3 时会卡住。要获得 pypyodbc,我只需运行 pip install pypyodbc

  2. Access 中的所有日期/时间值都有日期和时间部分。为了使日期/时间值在 Access 中默认显示为仅时间,我们需要为其分配“神奇”日期 1899-12-30。 (即 Access 中CDate(0) 对应的日期。)

【讨论】:

    猜你喜欢
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多