Python:将二维数组插入Mysql数据库

时间:2018-12-21 06:15:53

标签: python mysql

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

这是我的代码。我想将myArray [r]插入数据库,但是程序给我“错误”消息。如何将所有项目(例如[['example1','example2'])插入1行。

2 个答案:

答案 0 :(得分:1)

据我了解,这些都是标题,我们可以先flatten the list,然后再插入.executemany()。看起来多么简洁和美丽:

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

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

cur.commit()

答案 1 :(得分:0)

您可以先插入myArray中的每个项目,然后再尝试插入它们。

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

这应该给您以下标题:

"example1,example2"
"value1,value2"