如何明确引用字符串值(Python DB API / Psycopg2) [英] How to quote a string value explicitly (Python DB API/Psycopg2)

查看:127
本文介绍了如何明确引用字符串值(Python DB API / Psycopg2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我想对字符串值进行明确的引用(成为构造的SQL查询的一部分),而不是等待由 cursor.execute 方法对其第二个参数的内容。

For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by cursor.execute method on contents of its second parameter.

通过隐含引用我的意思是:

By "implicit quotation" I mean:

value = "Unsafe string"
query = "SELECT * FROM some_table WHERE some_char_field = %s;"
cursor.execute( query, (value,) ) # value will be correctly quoted

我喜欢这样的:

value = "Unsafe string"
query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \
    READY_TO_USE_QUOTING_FUNCTION(value)
cursor.execute( query ) # value will be correctly quoted, too

由Python DB API规范预期的低级别 READY_TO_USE_QUOTING_FUNCTION (在 PEP 249 文件)。如果没有,Psycopg2可能提供这样的功能?如果没有,Django可能提供这样的功能?我不想自己写这样的函数...

Is such low level READY_TO_USE_QUOTING_FUNCTION expected by Python DB API specification (I couldn't find such functionality in PEP 249 document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...

推荐答案

好的,所以我很好奇,的psycopg2。原来我没有进一步比例文件夹:)

Ok, so I was curious and went and looked at the source of psycopg2. Turns out I didn't have to go further than the examples folder :)

是的,这是psycopg2特定的。基本上,如果你只想引用一个字符串,你可以这样做:

And yes, this is psycopg2-specific. Basically, if you just want to quote a string you'd do this:

from psycopg2.extensions import adapt

print adapt("Hello World'; DROP DATABASE World;")

但是你可能想做的是写和注册自己的适配器;

But what you probably want to do is to write and register your own adapter;

在psycopg2的示例文件夹中,您可以找到文件'myfirstrecipe.py'有一个如何以特殊方式投射和引用特定类型的示例。

In the examples folder of psycopg2 you find the file 'myfirstrecipe.py' there is an example of how to cast and quote a specific type in a special way.

如果您有要做的东西的对象,可以创建符合IPsycopgSQLQuote协议的适配器(请参阅pydocs for myfirstrecipe.py-example ...实际上是唯一可以找到这个名称的引用),引用你的对象,然后注册它:

If you have objects for the stuff you want to do, you can just create an adapter that conforms to the 'IPsycopgSQLQuote' protocol (see pydocs for the myfirstrecipe.py-example...actually that's the only reference I can find to that name) that quotes your object and then registering it like so:

from psycopg2.extensions import register_adapter

register_adapter(mytype, myadapter)

另外,其他的例子很有趣; ESP。 'dialtone.py''simple.py'

Also, the other examples are interesting; esp. 'dialtone.py' and 'simple.py'.

这篇关于如何明确引用字符串值(Python DB API / Psycopg2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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