Update database with multiple SQL Statments

柔情痞子 提交于 2019-12-03 04:04:07
Rao

At-last after a long research on docs and help. I could able to solve the issue.

Using a for loop at cursor.execute with multi=True worked. I don't know why we need to loop through.

for result in cursor.execute(SQL, multi=True):
    pass

Without loop just cursor.execute(SQL, multi=True) did not do any changes in the database.

import mysql.connector

cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()

SQL = '''
    update my_table 
    set 
    LAY = 'P6682'
    , BLK = 'P6682'
    , ANI = 'P6682'
    where
    Shot = 'SH01';

    update my_table 
    set 
    LAY = '1863'
    , BLK = '1863'
    , ANI = '1863'
    where
    Shot = 'SH02'
'''

for result in cursor.execute(SQL, multi=True):
    pass

cnx.commit()
cur.close()
cnx.close()
cnx.disconnect()

Looking at the MySQL docs

If multi is set to True, execute() is able to execute multiple statements specified in the operation string. It returns an iterator that enables processing the result of each statement. However, using parameters does not work well in this case, and it is usually a good idea to execute each statement on its own.

so setting multi=True returns an iterator and if you just want to loop through each statement, the other solution offered works well:

for result in cursor.execute(SQL, multi=True):
    pass

Did you miss somekind of commit

cnx.commit()

MySQL reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!