Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

python - Inserting a list holding multiple values in MySQL using pymysql

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
vals = [["TEST1", 1], ["TEST2", 2]]

with connection.cursor() as cursor:
    cursor.executemany("insert into test(prop, val) values (%s, %s)", vals )
    connection.commit()

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 |
+----+-------+------+---------------------+

Adapted from https://groups.google.com/forum/#!searchin/pymysql-users/insert%7Csort:relevance/pymysql-users/4_D8bYusodc/EHFxjRh89XEJ


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...