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?

查看:1782
本文介绍了MySQL为什么cursor.execute(sql,multi = True)不起作用,但是2 cursor.execute(sql)起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有效:

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

此代码不起作用:

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

两个代码之间的区别只是cursor.execute(). 在第一个代码中,我们有2个cursor.execute(sql). 在第二个代码中,我们有1个cursor.execute(sql,multi = True)和2条SQL语句.

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?

推荐答案

此语句:

cursor.execute(sql, multi=True)

在结果上创建一个迭代器.看起来很懒(即仅根据需要执行SQL语句).您永远不会要求第二条语句的结果,因此它仅执行第一条语句.试试:

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

通常,最好只使用单独的execute()调用.

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

这篇关于MySQL为什么cursor.execute(sql,multi = True)不起作用,但是2 cursor.execute(sql)起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆