pymysql之execute问题

最近在使用pymysql过程中,发现了一个奇怪的地方:

之前有一个地方写的

cursor.execute("select * from table1 where name = %s", name)

用法没问题,而在最近一次写脚本的时候,这样写

cursor.execute("delete from %s where data_date='2017-11-29'", table2)

这个时候报错了

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version……

修改成

cursor.execute("delete from %s where data_date='2017-11-29'" % table2)

或者

cursor.execute("delete from {} where data_date='2017-11-29'".format(table2))

就没问题了。但是对之前这样用没报错感到了疑问……查了资料后得知

在pymysql的execute方法中,执行的mysql语句中用%s替换的参数外加上了单引号。而在mysql的语句中表名和列名外都不能加单引号,而值则可以加单引号。

这下明白了……

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。