gpt4 book ai didi

python - 如何在 Python 中编写正确的 MySQL Insert 语句?

转载 作者:行者123 更新时间:2023-11-29 15:43:48 25 4
gpt4 key购买 nike

我正在尝试从 Python 将两列数据插入到 MySQL 表中。我想我的插入语句是正确的。但我仍然收到 1064 错误代码。

这适用于 MySQL 服务器版本 8.0.12 和 Python 3.7。我尝试过改变插入动态变量的不同方法。

#alter is the data value read from serial port

sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")

我收到此错误消息错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1

我希望这些读取的标签值能够成功插入。

最佳答案

MySQL(以及大多数其他类型的 SQL)中的标识符(例如列名和表名)不使用单引号。它们要么不带引号,要么带双引号,或者在 MySQL 中可能带反引号。试试这个版本:

sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()

关于python - 如何在 Python 中编写正确的 MySQL Insert 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com