使用pymysql在MySQL中插入包含多个值的列表 [英] Inserting a list holding multiple values in MySQL using pymysql
问题描述
我有一个保存名称的数据库,我必须创建一个新列表,该列表将保存ID,名称和性别等值,并将其插入当前数据库中.我必须创建一个不在数据库中的名称列表.因此,我只检查了3个名称并尝试使用它们.
I have a database holding names, and I have to create a new list which will hold such values as ID, name, and gender and insert it in the current database. I have to create a list of the names which are not in the database yet. So I simply checked only 3 names and trying to work with them.
我不确定应该创建哪种列表,以及如何循环浏览以正确的方式插入所有新值.
I am not sure what sort of list I suppose to create and how I can loop through it to insert all the new values in the proper way.
这就是我到目前为止所拥有的:
That's what I have so far:
mylist = [["Betty Beth", "1", "Female"], ["John Cena", "2", "Male"]]
@get("/list_actors")
def list_actors():
with connection.cursor() as cursor:
sql = "INSERT INTO imdb VALUES (mylist)"
cursor.execute(sql)
connection.commit()
return "done"
我对此材料非常陌生,因此我将不胜感激.预先感谢!
I am very new to this material so I will appreciate any help. Thanks in advance!
推荐答案
vals = [["TEST1", 1], ["TEST2", 2]]
with connection.cursor() as cursor:
cursor.executemany("insert into test(prop, val) values (%s, %s)", vals )
connection.commit()
mysql>从测试中选择*;
mysql> select * from test;
+----+-------+------+---------------------+
| id | prop | val | ts |
+----+-------+------+---------------------+
| 1 | TEST1 | 1 | 2017-05-19 09:46:16 |
| 2 | TEST2 | 2 | 2017-05-19 09:46:16 |
+----+-------+------+---------------------+
这篇关于使用pymysql在MySQL中插入包含多个值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!