4

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()
asked Dec 8, 2015 at 17:19

1 Answer 1

2

You can do that "in one go" via executemany():

cur.executemany("""
 INSERT INTO 
 cord
 (x, y, z)
 VALUES
 (%s, %s, %s)
""", asd)
db.commit()
answered Dec 8, 2015 at 17:26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.