Reputation:
I have database named : test; table named: cord; rows named: id ; x ; y ; z.
Lets say i have 2d array like this:
asd = [[1.25,2.45,3.65],[2.78,3.59,1.58]......]
I want to insert asd[0][0] element into x row, asd [0][1] into y row, asd[0][2] into z row, asd [1][0] into x row, asd[1][1] into y row, asd [1][2] into z row and etc if i have more aray elements.
My code so far(i know that insert function defines only 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()
Upvotes: 4
Views: 2991
Reputation: 473893
You can do that "in one go" via executemany()
:
cur.executemany("""
INSERT INTO
cord
(x, y, z)
VALUES
(%s, %s, %s)
""", asd)
db.commit()
Upvotes: 2