【问题标题】:How to insert values from numpy into sql database with given columns?如何将numpy中的值插入到具有给定列的sql数据库中?
【发布时间】:2018-08-14 21:02:55
【问题描述】:

我需要在 Mariadb 的表中插入一些列。表名为 Customer,有 6 列,A、B、C、D、E、F。主键在第一列,B 列有地址,C、D 和 E 包含 None 值,F 是邮政编码。

我有一个遵循类似格式的熊猫数据框。我通过执行以下操作将其转换为 numpy 数组:

data = df.iloc[:,1:4].values

因此数据是一个包含 3 列的 numpy 数组,我需要将其插入 C、D 和 E。我试过了:

query = """
Insert Into Customer (C,D,E) VALUES (?,?,?)
"""
cur.executemany(query,data)
cur.commit()

但我得到一个错误:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: python-3.x pandas numpy mysql-python


    【解决方案1】:

    我解决了。虽然很慢...

    query = """
    Alter Customer SET
    C = %s
    D = %s
    E = %s
    where A = %s
    """
    
    for row in data:
        cur.execute(query,args=(row[1],row[2],row[3],row[0])
    con.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      相关资源
      最近更新 更多