将Python列表插入Mysql时出错

时间:2018-03-22 05:25:38

标签: python mysql

有一个示例Python列表如下:

data = [
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas')
]

尝试将此列表插入到My Sql数据库中,其表名为“test”,如下所示:

import MySQLdb as my

db = my.connect()

cursor = db.cursor()

data = [
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas')
]

ddt = str(data)

cursor.executemany('INSERT into test VALUES(%s, %s, %s,%s)' %  ddt)

db.commit()  

db.close()

收到错误说:

not enough arguments for format string

表包含4列:test1,test2,test3,test4。我知道我在某个地方犯了一个愚蠢的错误,但似乎无法找到它。

2 个答案:

答案 0 :(得分:0)

完整代码可以是这种类型::

import MySQLdb
import MySQLdb.cursors
encoding = "utf8mb4"
db = MySQLdb.connect(
    host='',
    user='',
    passwd='',
    db='',
    compress=1,
    port=,
    charset='utf8mb4',
    use_unicode=True,
)
cursor = db.cursor()
data = [
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas'),
('Jane','dffd','sdas','sdas')
]

sql = "INSERT INTO test VALUES %s;" %(str(tuple(data)).replace('((','(').replace('))',')'))
print(sql) // you can print the sql query and verify to insert data on test mysqlworkbech for confirm data structure is 
cursor.execute(sql)
db.commit()  
db.close()

答案 1 :(得分:-1)

试试这个:

cursor.executemany('INSERT into test VALUES(%s, %s, %s,%s)',data)

或者

cursor.execute("INSERT INTO test VALUES %s;" %(str(tuple(data)).replace('((','(').replace('))',')')))