【问题标题】:Python: insert 2D array into MySQL tablePython:将二维数组插入 MySQL 表
【发布时间】:2016-03-13 17:44:42
【问题描述】:

我有一个名为:test 的数据库;表名:cord; 行命名: id ; X ;是; z。

假设我有这样的二维数组:

asd = [[1.25,2.45,3.65],[2.78,3.59,1.58]......]

我想将 asd[0][0] 元素插入 x 行, asd [0][1] 插入 y 行, asd[0][2] 插入 z 行, asd [1][0] 插入 x行,asd[1][1] 到 y 行,asd [1][2] 到 z 行等等,如果我有更多的 aray 元素。

到目前为止我的代码(我知道插入函数只定义了 x):

import MySQLdb

# Open database connection
db = MySQLdb.connect(host="localhost",port= 3307,user="root",passwd="usbw" , db = "test")

# prepare a cursor object using cursor() method
cur = db.cursor()

# Create table as per requirement
 asd = [[1.25,2.45,3.65],[2.78,3.59,1.58]]
 for x in asd:
 cur.execute("INSERT INTO cord(x) VALUES(%s)",x)
 db.commit()

# disconnect from server
db.close()

【问题讨论】:

    标签: python mysql arrays python-2.7


    【解决方案1】:

    您可以通过executemany()“一次性”完成此操作:

    cur.executemany("""
        INSERT INTO 
            cord
            (x, y, z)
        VALUES
            (%s, %s, %s)
    """, asd)
    db.commit()
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      相关资源
      最近更新 更多