[英]Insert lists into mysql in column wise in python
i have 3 list 我有3个清单
list1=[3, 4, 5, 6, 9]
list2=[1, 10, 5, 2, 1]
list3=[5, 53, 26, 11, 5]
how to insert this data into mysql database in column wise. 如何以列方式将此数据插入到mysql数据库中。 each list should be stored in a column.I knew to store it row wise using
cursor.executemany(sqlquery,lists)
. 每个列表都应存储在一列中。我知道使用
cursor.executemany(sqlquery,lists)
以行方式存储它。 Please help me. 请帮我。
You can do this by using pandas
: 你可以通过使用
pandas
来做到这一点:
Convert the lists into a Pandas dataframe : 将列表转换为Pandas数据帧 :
In [1644]: df = pd.DataFrame({'list1':list1,'list2':list2,'list3':list3})
In [1645]: df
Out[1645]:
list1 list2 list3
0 3 1 5
1 4 10 53
2 5 5 26
3 6 2 11
4 9 1 5
Use to_sql
method to write into mysql table : 使用
to_sql
方法写入mysql表 :
df.to_sql(con=con, name='mytable', if_exists='replace', flavor='mysql')
If you want only using cursor.executemany
. 如果你只想使用
cursor.executemany
。 So you can transform three lists into one by combining data from the same position. 因此,您可以通过组合来自相同位置的数据将三个列表转换为一个。
list1=[3, 4, 5, 6, 9]
list2=[1, 10, 5, 2, 1]
list3=[5, 53, 26, 11, 5]
print(list(zip(list1,list2,list3)))
# [(3, 1, 5), (4, 10, 53), (5, 5, 26), (6, 2, 11), (9, 1, 5)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.