简体   繁体   English

MySQL为什么cursor.execute(sql,multi = True)不起作用,但是2 cursor.execute(sql)起作用?

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

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(). 两种代码之间的区别只是cursor.execute()。 In the first code, we have 2 cursor.execute(sql). 在第一个代码中,我们有2个cursor.execute(sql)。 In the second code, we have 1 cursor.execute(sql, multi=True) with 2 SQL statements. 在第二个代码中,我们有1个cursor.execute(sql,multi = True)和2条SQL语句。

Both codes doesn't rise errors, but, the second code does not insert rows. 两种代码都不会引发错误,但是第二种代码不会插入行。

why just the first code works? 为什么只有第一个代码有效?

This statement: 这个说法:

cursor.execute(sql, multi=True)

creates an iterator over the results. 在结果上创建一个迭代器。 It looks like it's lazy (ie, it executes SQL statements only as needed). 看起来很懒(即仅根据需要执行SQL语句)。 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. 通常,最好只使用单独的execute()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM