asIs 和 sql 模块之间的 psycopg2 区别 [英] psycopg2 difference between AsIs and sql module

查看:102
本文介绍了asIs 和 sql 模块之间的 psycopg2 区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在查询中动态选择表名,我曾经使用 psycopg2.extensions 中的 AsIs() ( http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.AsIs ),与以下语法:

To choose dynamically a table name in a query I used to use AsIs() from psycopg2.extensions ( http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.AsIs ), with the following syntax:

cur.execute("SELECT * FROM %s WHERE id = %s;", (AsIs('table_name'), id))

但是,文档现在建议使用 2.7 版中提供的新 psycopg2.sql 模块( http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql ),语法如下:

However, the documentation now recommends to use the new psycopg2.sql module available in version 2.7 ( http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql ) with the following syntax:

from psycopg2 import sql

cur.execute(
    sql.SQL("SELECT * FROM {} WHERE id = %s;")
        .format(sql.Identifier('table_name')), (id, )

除了 sql 模块公开的对象可以直接传递给 execute() 之外,这两个选项之间有什么区别?

What's the difference between those two options besides the fact that objects exposed by the sql module can be passed directly to execute()?

推荐答案

AsIs 是...如果它包含需要引用的字符,它不会对表名执行任何转义.sql 模块中的对象反而知道什么是 一个标识符.

AsIs is... as it is. It won't perform any escape of the table name, if it contains characters need quoting. The objects in the sql module instead know what is an identifier.

更巧妙的是,AsIs 仅用于参数值:如果当前有效,则主要是实现意外,将来行为可能会改变.不应使用查询值来表示查询的可变部分,例如表名或字段名.

More subtly, AsIs is for parameter values only: if currently works is mostly an implementation accident and in the future the behaviour may change. Query values should not be used to represent variable parts of the query, such as table or field names.

这篇关于asIs 和 sql 模块之间的 psycopg2 区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆