Update database with multiple SQL Statments

后端 未结 4 1337
终归单人心
终归单人心 2021-02-06 06:48

I am using mysql connector.Python 1.0.9 downloaded from MySQL site.

I have a sample table here

DROP TABLE IF EXISTS my_table; 
CREATE TABLE my_table
(id          


        
4条回答
  •  野的像风
    2021-02-06 07:37

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

提交回复
热议问题