在数据库 MySQLdb Python3.6 中插入列表

Insert list in database MySQLdb Python3.6

我在使用 MySQLdb 驱动程序将列表插入 mysql 数据库时遇到问题。

 import MySQLdb

db = MySQLdb.connect("localhost", "user", "password", "db")

c = db.cursor() 
cities = ["New York", "NY", 8400000]

sql = "INSERT INTO projecten.population(city, state, population) VALUES(?, ?, ?)", cities

try:
    c.execute(sql)
    db.commit()
except MySQLdb.OperationalError:
    print("error")
finally:
    db.close()

这是错误

TypeError: a bytes-like object is required, not 'tuple'

可能您希望将字符串格式化程序与元组一起使用 -

>>> sql = "INSERT INTO projecten.population(city, state, population) VALUES('%s', '%s', '%s')" % tuple(cities)
>>> sql
"INSERT INTO projecten.population(city, state, population) VALUES('New York', 'NY', '8400000')"

SQL 语句应正确传递值。

import MySQLdb
db = MySQLdb.connect("localhost", "user", "password", "db")
c = db.cursor() 
cities = ["New York", "NY", 8400000]
sql = "INSERT INTO projecten.population(city, state, population) VALUES({0}, {1}, {2})".format(*cities)
try:
    c.execute(sql)
    db.commit()
except MySQLdb.OperationalError:
    print("error")
finally:
    db.close()

我得到了答案

c.executemany("INSERT INTO projecten.population(city, state, population) VALUES(%s, %s, %s)", (cities))