V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dafuyang
V2EX  ›  Python

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

  •  
  •   dafuyang · 2023-01-30 23:16:56 +08:00 · 1411 次点击
    这是一个创建于 423 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如这种查询,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. 想了解一下占位符需不需要根据查询字段的类型去更换呢
    5 条回复    2023-01-31 17:50:13 +08:00
    maocat
        1
    maocat  
       2023-01-31 00:23:07 +08:00
    三条语句实际上都是 uid = 12

    golang 里有 %#v 可以额外输出类型名,python 里就不知道了
    centralpark
        2
    centralpark  
       2023-01-31 00:37:50 +08:00
    建议直接上 sqlalchemy ,而且用原生 sql 也不应该自己做字符串拼接,应该用 ?来做占位符。
    Gakho
        3
    Gakho  
       2023-01-31 08:38:54 +08:00
    你可能需要了解一下 PEP249 的 paramstyle
    lookStupiToForce
        4
    lookStupiToForce  
       2023-01-31 11:03:10 +08:00
    你如果不做类型检查和文本检查,就要小心注入攻击
    duckyrain
        5
    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.
    """
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5198 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:27 · PVG 17:27 · LAX 02:27 · JFK 05:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.