【发布时间】: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'): 从字符串转换日期和/或时间时转换失败。
【问题讨论】:
-
类似pyodbc-dataerror。请删除您的重复代码并改为显示您的
CREATE TABLE ...。 -
@stovfl 我认为它不仅不能将日期/时间数据插入到表中。整个想法和python代码都有问题。我认为我上面的第二个 python 代码也有其他问题。顺便说一句,谢谢你的信息
-
尝试隔离一个问题并提出minimal reproducible example