Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL why cursor.execute(sql, multi=True) does not work but 2 cursor.execute(sql) works?

Tags:

python

mysql

This code works:

sql = """TRUNCATE TABLE product_groups;"""
cursor.execute(sql)

sql = """INSERT INTO product_groups (origin, type, name, brand, concentration, gender) 
            SELECT origin, type, name, brand, concentration, gender
            FROM products
            GROUP BY origin, type, name, brand, concentration, gender
            ORDER BY brand, name;"""
cursor.execute(sql)

cursor.close()
conn.commit()
conn.close()

this code does not work:

sql = """TRUNCATE TABLE product_groups;
            INSERT INTO product_groups (origin, type, name, brand, concentration, gender) 
            SELECT origin, type, name, brand, concentration, gender
            FROM products
            GROUP BY origin, type, name, brand, concentration, gender
            ORDER BY brand, name;"""
cursor.execute(sql, multi=True)

cursor.close()
conn.commit()
conn.close()

The difference between two codes is just the cursor.execute(). In the first code, we have 2 cursor.execute(sql). In the second code, we have 1 cursor.execute(sql, multi=True) with 2 SQL statements.

Both codes doesn't rise errors, but, the second code does not insert rows.

why just the first code works?

like image 804
Andy Schmitt Avatar asked Jun 01 '26 15:06

Andy Schmitt


1 Answers

This statement:

cursor.execute(sql, multi=True)

creates an iterator over the results. It looks like it's lazy (i.e., it executes SQL statements only as needed). You're never asking for the results for the second statement, so it is only executing the first one. Try:

for _ in cursor.execute(sql, multi=True): pass

In general it's better to just use separate execute() calls.

like image 197
kindall Avatar answered Jun 03 '26 04:06

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!