推荐学习书目
› 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
1989922yan
V2EX  ›  Python

sqlalchemy 或者 底层 mysqldb 如何防止 sql 注入??

  •  
  •   1989922yan · Dec 29, 2014 · 9657 views
    This topic created in 4328 days ago, the information mentioned may be changed or developed.
    12 replies  •  2015-01-06 15:50:53 +08:00
    janxin
    janxin
    Dec 29, 2014
    1
    MySQLdb:

    不要直接拼装SQL语句,比如:
    cmd = "select tab where id='%s'" % id
    curs.execute(cmd)

    如果要拼装,参数一定要用MySQLdb.escape_string()过一下。当然,下面的写法更省事:

    cmd = "select people set name=%s where id=%s"
    curs.execute(cmd, (name, id))

    sqlalchemy没用过,不清楚了,应该也是默认过滤的,只要你不直接传SQL进来
    janxin
    janxin
    Dec 29, 2014
    2
    第二个SQL语句不对:
    cmd = "select tab where id='%s'"
    curs.execute(cmd, (id,))
    010blue
    010blue
    Dec 29, 2014❤️1
    3
    底层 mysqldb防注入这个想法挺前卫的,可以在mysql数据库之前做一层mysql-proxy,通过这个来对接收的sql语句做一次检查过滤,当然还能顺便把读写给做了;如果再底层到mysql服务器的话,估计要写存储过程了,这个也是要改程序的
    wingyiu
    wingyiu
    Dec 29, 2014
    4
    @janxin `cmd = "select tab where id='%s'"` => `cmd = "select tab where id=%s"`
    MasterYoda
    MasterYoda
    Dec 30, 2014
    5
    Prestatement会好一些。
    1989922yan
    1989922yan
    OP
    Dec 30, 2014
    6
    @janxin
    完美答案。谢谢。
    1989922yan
    1989922yan
    OP
    Dec 30, 2014
    7
    @010blue
    跟数据库交互的api,还是有很多需要注意的,还是需要多学习
    1989922yan
    1989922yan
    OP
    Dec 30, 2014
    8
    @MasterYoda
    刚刚查了查,了解了,java中有的概念,一直python感觉可以学习java很多框架经验啊
    MasterYoda
    MasterYoda
    Dec 30, 2014❤️1
    9
    @1989922yan
    倒不算Java概念,可以叫绑定参数还是什么的。
    MySQL本身支持而已,Prepared Statement http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
    各个语言的库基本都支持。
    1989922yan
    1989922yan
    OP
    Dec 30, 2014
    10
    @MasterYoda
    新技能。
    我先看看。
    THX:)
    010blue
    010blue
    Jan 6, 2015
    11
    @1989922yan 对,解决安全问题的最佳方案还是在架构层面上,单纯依靠程序员的经验是容易出问题的
    1989922yan
    1989922yan
    OP
    Jan 6, 2015
    12
    @010blue

    扯大了。
    只是说说sql注入,防范方法也就是那些。
    架构也是程序员写的,架构师也都是写积累的。
    大家接触的项目,真的跟12306一样大吗?
    能出了问题让解决了才开心。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2969 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 10:47 · PVG 18:47 · LAX 02:47 · JFK 05:47
    ♥ Do have faith in what you're doing.