Python向数据库内插入变量后数据库内无变化

img

img


import pymysql

a = (('666', '666', '666', '666'), ('666', '666', '666', '666'))
mydb = pymysql.connect(host="localhost", user="root", passwd="", database='123')
mycursor = mydb.cursor()
f'INSERT INTO 数据 VALUES {a}'
mydb.commit()
print(mycursor.rowcount, "was inserted.")
mydb.close()
哪里出错了,应该怎么解决呢

该回答引用GPTᴼᴾᴱᴺᴬᴵ
您需要将SQL语句传递给 execute() 方法,并将语句中的占位符替换为您要插入的值。

以下是修改后的代码示例:

import pymysql

a = (('666', '666', '666', '666'), ('666', '666', '666', '666'))

mydb = pymysql.connect(host="localhost", user="root", passwd="", database='123')
mycursor = mydb.cursor()

sql = "INSERT INTO 数据 VALUES (%s, %s, %s, %s)"
mycursor.executemany(sql, a)

mydb.commit()
print(mycursor.rowcount, "was inserted.")
mydb.close()


在上面的代码中,我们使用了 %s 占位符来表示要插入的值,然后在 executemany() 方法中将占位符替换为 a 变量中的值。

同时,也建议您在插入完数据后关闭游标和数据库连接。