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

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值