Python: insert a 2D array into a MySQL table

I have a database named: test; table named: cord; lines with the name: id; X; y; g.

Let's say that I have a 2d array as follows:

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

I want to insert the asd [0] [0] element into the string x, asd [0] [1] into the y string, asd [0] [2] into the z string, asd [1] [0] into the x row, asd [ 1] [1] in y row, asd [1] [2] in z string, etc., if I have more aray elements.

My code is still (I know that the insert function only defines 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()
+4
source share
1 answer

You can do this in one go through executemany():

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

Source: https://habr.com/ru/post/1619071/


All Articles