V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Jan 30, 2023 · 2551 views
    This topic created in 1186 days ago, the information mentioned may be changed or developed.

    比如这种查询,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 replies    2023-01-31 17:50:13 +08:00
    maocat
        1
    maocat  
       Jan 31, 2023
    三条语句实际上都是 uid = 12

    golang 里有 %#v 可以额外输出类型名,python 里就不知道了
    centralpark
        2
    centralpark  
       Jan 31, 2023
    建议直接上 sqlalchemy ,而且用原生 sql 也不应该自己做字符串拼接,应该用 ?来做占位符。
    Gakho
        3
    Gakho  
       Jan 31, 2023
    你可能需要了解一下 PEP249 的 paramstyle
    lookStupiToForce
        4
    lookStupiToForce  
       Jan 31, 2023
    你如果不做类型检查和文本检查,就要小心注入攻击
    duckyrain
        5
    duckyrain  
       Jan 31, 2023
    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.
    """
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2383 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 11:40 · PVG 19:40 · LAX 04:40 · JFK 07:40
    ♥ Do have faith in what you're doing.