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
Ayase
V2EX  ›  Python

如何去掉Python SQL中的引号

  •  
  •   Ayase · 2013-08-12 11:34:41 +08:00 · 4313 次点击
    这是一个创建于 3911 天前的主题,其中的信息可能已经有所发展或是发生改变。
    大概是这样的
    common = form["common"]
    query = "UPDATE tb SET %s = %s WHERE id = %s"
    cursor.execute(query, [common, field, updtae_id])

    变量common代替字段名title。
    然后common替代第一个 %s 时,SQL报错:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''title' = 'title3' WHERE id = '3'' at line 1"

    就是 common 被自动加上引号了……如何才可以不让它有引号呢?
    Python新手,谢谢指教……
    3 条回复    1970-01-01 08:00:00 +08:00
    nybux
        1
    nybux  
       2013-08-12 11:46:27 +08:00   ❤️ 1
    你这种不是变量绑定,是动态sql了,你还是自己先在字符串层面把column都补好
    janxin
        2
    janxin  
       2013-08-12 14:49:23 +08:00   ❤️ 1
    楼主用的什么SQL库呢?如果是Mysql-python的话,可以用:
    ```
    MySQLdb.escape_string()
    ```

    还有楼主你这么写是有SQL注入漏洞的....
    lqs
        3
    lqs  
       2013-08-12 16:44:47 +08:00   ❤️ 1
    @janxin 楼主这样是参数化查询,会自动判断类型并转义,不会有SQL注入漏洞。反而手动去escape_string容易漏写。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1622 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:43 · PVG 00:43 · LAX 09:43 · JFK 12:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.