在数据库MySQLdb Python3.6

时间:2017-08-10 01:33:20

标签: python-3.x mysql-python python-3.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'

2 个答案:

答案 0 :(得分:0)

可能是你想要使用带有元组的字符串格式化程序 -

>>> 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')"

答案 1 :(得分:0)

应该使用值正确传递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()