【问题标题】:What is the correct way to form MySQL queries in python?在 python 中形成 MySQL 查询的正确方法是什么?
【发布时间】:2010-10-16 09:20:06
【问题描述】:

我是 python 新手,我来自 PHP 的土地。我根据我的 PHP 知识在 python 中构建了一个这样的 SQL 查询,我收到警告和错误

cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid))
# rowcount here is int

形成查询的正确方法是什么?

另外,如何转义字符串以形成 SQL 安全字符串?比如如果我想转义 -、'、" 等,我曾经使用 addlashes。我们如何在 python 中做到这一点?

谢谢

【问题讨论】:

    标签: python sql mysql


    【解决方案1】:

    首先,是时候学习使用 Matus 表达的方法安全地将变量传递给查询了。更清晰,

    tuple = (foovar, barvar)
    cursor.execute("QUERY WHERE foo = ? AND bar = ?", tuple)
    

    如果你只需要传递一个变量,你仍然必须把它做成一个元组:在末尾插入逗号告诉 Python 把它当作一个元组:tuple = (onevar,)

    你的例子是这样的:

    cursor_.execute("update posts set comment_count = comment_count + ? where id = ?",
                    (cursor_.rowcount, postid))
    

    你也可以像这样使用命名参数

    cursor_.execute("update posts set comment_count = comment_count + :count where id = :id",
                    {"count": cursor_.rowcount, "id": postid})
    

    这一次参数不是元组,而是由成对的"key": value 组成的字典。

    【讨论】:

    • 我可以使用这样的东西吗? cursor.execute("更新帖子集comment_count = %s where postid = %d",cursor_.rowcount,postid)
    • @arbithero:是的,我想你可以。从wiki.python.org/moin/DbApiFaq 我也将其解释为一种安全的方法。你从哪里得到这个例子的?我在任何地方都找不到%d
    • @arbithero:添加了一些关于命名查询的示例,如果看起来更好的话。
    【解决方案2】:

    来自python手册:

    t = (symbol,)
    
    c.execute( 'select * from stocks where symbol=?', t )
    

    这样可以防止 SQL 注入(假设这是您所指的 SQL 安全)并且还解决了格式问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-27
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多