【问题标题】:pyodbc: Conversion failed when converting date and/or time from character stringpyodbc:从字符串转换日期和/或时间时转换失败
【发布时间】:2018-11-17 09:25:59
【问题描述】:

我是 python 新手。目前,我有一个 python 代码可以将新数据插入到我的 Microsoft SQL 数据库中,我这样做如下:

import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DESKTOP-H7KQUT1;"
                      "Database=SAOS1;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()


print ('Inserting a new row into table')
#Insert Query
tsql = "INSERT INTO attendance (Atd_Date, Atd_InTime, Atd_OutTime, SID) VALUES (?,?,?,?);"
with cursor.execute(tsql,'2018/11/14','07:11:34','14:32:11','18010321'):
    print ('Successfuly Inserted!')

但是,我在另一边有一个 Arduino 项目,它使用指纹记录学生出勤率。找到匹配项时,串行监视器将显示输出。我的arduino代码是:

void setup()
   {
     ....
   }
void loop()
   {
     ...
     //Found a match
     Serial.println("{'SID':"+ String(finger.fingerID) +",'Time':"+ String(timeString) +"}");
   }

示例输出将如下所示:

{'SID':1,'Time':07:11:13}

我想从串行中捕获此输出,并让我的 python 代码获取此输出并将其存储到 MSSQL 数据库中。我指的是这个website 所以,我是这样做的:

import pyodbc
import serial
import time
import datetime
import ast
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DESKTOP-H7KQUT1;"
                      "Database=SAOS1;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()

#initial serial port
arduino = serial.Serial('COM4', 9600, timeout=.1)
#fetch data from serial
data = arduino.readline()[:-2].decode("utf-8")
if data!="":

        SID = ast.literal_eval(data)['SID']
        Atd_InTime = ast.literal_eval(data)['Time']

print ('Inserting a new row into table')
#Insert Query
tsql = "INSERT INTO attendance (Atd_Date, Atd_InTime, Atd_OutTime, SID) VALUES (?,?,?,?);"
with cursor.execute(tsql,'2018/11/14','Time','14:32:11','SID'):
    print ('Successfuly Inserted!')

但我没有这样做。我不确定这是不是正确的方法。此外,我收到此错误:

第 24 行,在 with cursor.execute(tsql,'2018/11/14','Time','14:32:11','SID'): 从字符串转换日期和/或时间时转换失败。

【问题讨论】:

标签: python pyodbc


【解决方案1】:
cursor.execute(tsql,'2018/11/14','Time','14:32:11','SID')

第二个参数值(.execute 方法的第三个参数)是字符串文字 'Time'。 SQL Server 抱怨它无法将该字符串转换为有效的时间值。

如果您调整 Arduino 代码以返回

{'SID':1,'Time':'07:11:13'}

那么你可以使用

cursor.execute(tsql,'2018/11/14',Atd_InTime,'14:32:11',SID)

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多