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.

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()
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"

Comments

Your Answer

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.