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.
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
asked Dec 21, 2018 at 6:15
Omer Tekbiyik
4,8041 gold badge20 silver badges29 bronze badges
2 Answers 2
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()
answered Dec 21, 2018 at 6:30
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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"
answered Dec 21, 2018 at 6:52
fixatd
1,4041 gold badge13 silver badges22 bronze badges
Comments
default
titlevalues?