1
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
4
  • 1. Are you always gonna have 2 items per sublist? 2. Are both of these items title values? Commented Dec 21, 2018 at 6:25
  • No. My array items become from html parse so my per sublist have no 2 . Some of 15 some of 1. Randomly . I want to all this sublists are in 1 row in my database row named 'title'. Commented Dec 21, 2018 at 6:28
  • This is a terrible practice wrt/ proper relational model design - each value should be atomic. Commented Dec 21, 2018 at 8:10
  • I know that But I have thousands of data and Im using it for my DataMining project.Only I can access this database Commented Dec 21, 2018 at 9:14

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.