Python支持MySQL准备的语句吗?

2024-04-23 21:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在快速浏览了MySQLdb包的Cursor对象的execute()方法(我猜这是一种与mysql集成的事实上的包)之后,似乎(至少在默认情况下)它只做字符串插值和引号,而不是实际的参数化查询:

if args is not None:
    query = query % db.literal(args)

如果这不是字符串插值,那是什么?

在executemany中,它实际上尝试将insert/replace作为单个语句执行,而不是在循环中执行。差不多了,好像没有魔法。至少在其违约行为中没有。

编辑:哦,我刚刚意识到,模运算符可以被重写,但我觉得有点作弊,并修改了源代码。但在任何地方都找不到重写的mod

直接回答,没有。

joshperry's answer是一个很好的解释。

eugene y answer to a similar question

Check the MySQLdb Package Comments:

"Parameterization" is done in MySQLdb by escaping strings and then blindly interpolating them into the query, instead of using the MYSQL_STMT API. As a result unicode strings have to go through two intermediate representations (encoded string, escaped encoded string) before they're received by the database.

所以答案是:不,不是

大多数语言都提供了一种做泛型参数化语句的方法,Python也不例外。当使用参数化查询时,支持准备语句的数据库将自动这样做。

在python中,参数化查询如下所示:

cursor.execute("SELECT FROM tablename WHERE fieldname = %s", [value])

根据驱动程序的不同,参数化的特定样式可能会有所不同,您可以导入db模块,然后执行print yourmodule.paramstyle

来自PEP-249

paramstyle

       String constant stating the type of parameter marker
       formatting expected by the interface. Possible values are
       [2]:

           'qmark'         Question mark style, 
                           e.g. '...WHERE name=?'
           'numeric'       Numeric, positional style, 
                           e.g. '...WHERE name=:1'
           'named'         Named style, 
                           e.g. '...WHERE name=:name'
           'format'        ANSI C printf format codes, 
                           e.g. '...WHERE name=%s'
           'pyformat'      Python extended format codes, 
                           e.g. '...WHERE name=%(name)s'

相关问题 更多 >