Omer Tekbiyik
Omer Tekbiyik

Reputation: 4754

Python : insert 2 dimensional array into Mysql Database

myArray = [['example1','example2'], ['value1','value2']]
arraySize = len(myArray)
try:
for r in range(0,arraySize):
    try:
        cur.execute("INSERT INTO series(title) VALUES (%s)",(myArray[r]))
        conn.commit() 
    except:
        print "Error"
       conn.rollback()

This is my code. I want to insert myArray[r] to my Database but Program gives me "Error" message. How can I insert all items like (['example1','example2']) in 1 row.

Upvotes: 1

Views: 956

Answers (2)

fixatd
fixatd

Reputation: 1404

You can try joining each item in myArray first before trying to insert them.

myArray = [['example1','example2'], ['value1','value2']]
arraySize = len(myArray)
for r in range(0,arraySize):
    try:
        cur.execute(
              "INSERT INTO series(title) VALUES (%s)",
              (",".join(myArray[r]), ) # Merge the titles with a ,
        )
        conn.commit()
    except:
        print "Error"
       conn.rollback()

This should give you the following titles instead:

"example1,example2"
"value1,value2"

Upvotes: 0

alecxe
alecxe

Reputation: 473893

From what I understand, these are all titles and we could first flatten the list and then insert it with .executemany(). Look how concise and beautiful it is:

titles = [item for sublist in l for item in myArray]

cur.executemany("""
    INSERT INTO 
        series(title)
    VALUES (%s)""", titles)

cur.commit()

Upvotes: 1

Related Questions