兄弟们, pymsql 的查询里,占位符需不需要根据查询字段的类型去更换

2023-01-30 23:16:56 +08:00
 dafuyang

比如这种查询,uid 字段是 int 类型的,但是在 pymysql 的原生查询方式里,用%s 占位符,%d 占位符,int 类型,数字字符串查询:

sp.execute_cmd('select * from table where uid = %s', 12)
sp.execute_cmd('select * from table where uid = %s', '12')
sp.execute_cmd('select * from table where uid = %d', 12)

测试了一下都能查询到,问题有如下:

  1. 第一二种这种查询是不是就会触发数据库的类型隐式转换
  2. 想了解一下占位符需不需要根据查询字段的类型去更换呢
1454 次点击
所在节点    Python
5 条回复
maocat
2023-01-31 00:23:07 +08:00
三条语句实际上都是 uid = 12

golang 里有 %#v 可以额外输出类型名,python 里就不知道了
centralpark
2023-01-31 00:37:50 +08:00
建议直接上 sqlalchemy ,而且用原生 sql 也不应该自己做字符串拼接,应该用 ?来做占位符。
Gakho
2023-01-31 08:38:54 +08:00
你可能需要了解一下 PEP249 的 paramstyle
lookStupiToForce
2023-01-31 11:03:10 +08:00
你如果不做类型检查和文本检查,就要小心注入攻击
duckyrain
2023-01-31 17:50:13 +08:00
def execute(self, query, args=None):
"""Execute a query

:param str query: Query to execute.

:param args: parameters used with query. (optional)
:type args: tuple, list or dict

:return: Number of affected rows
:rtype: int

If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
"""

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/911800

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX