【问题标题】:Insert lists into mysql in column wise in python在python中按列将列表插入mysql
【发布时间】:2018-12-04 08:43:14
【问题描述】:

我有 3 个列表

list1=[3, 4, 5, 6, 9]
list2=[1, 10, 5, 2, 1]
list3=[5, 53, 26, 11, 5]

如何将这些数据按列插入 mysql 数据库。每个列表都应该存储在一个列中。我知道使用cursor.executemany(sqlquery,lists) 按行存储它。请帮帮我。

【问题讨论】:

    标签: python mysql python-3.x


    【解决方案1】:

    您可以使用pandas

    将列表转换为 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
    

    使用to_sql方法写入mysql表

    df.to_sql(con=con, name='mytable', if_exists='replace', flavor='mysql')
    

    【讨论】:

      【解决方案2】:

      如果您只想使用cursor.executemany。因此,您可以通过组合来自同一位置的数据将三个列表合二为一。

      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)]
      

      【讨论】:

        猜你喜欢
        • 2013-04-19
        • 2021-01-05
        • 2013-03-26
        • 1970-01-01
        • 2012-05-08
        • 2018-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多