使用psycopg2构造无连接的查询 [英] Use psycopg2 to construct queries without connection

查看:123
本文介绍了使用psycopg2构造无连接的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在野外,有几次我想收集数据.在这种情况下,我并不总是可以访问我的postgres数据库.

I have several occasions where I want to collect data when in the field. This is in situations where I do not always have access to my postgres database.

为使事情保持同步,如果我可以离线使用psycopg2函数来生成查询,这些查询可以被推迟,并且一旦我能够连接到数据库,那就太好了;处理所有被阻止的东西.

To keep things in sync, it would be excellent if I could use psycopg2 functions offline to generate queries that can be held back and once I am able to connect to the database; process everything that is held back.

我目前正在努力的一件事是psycopg2游标需要建立连接.

One thing I am currently struggling with is that the psycopg2 cursor requires a connection to be constructed.

我的问题是:

有没有一种方法可以使用游标在没有活动连接对象的情况下进行诸如抹灰之类的事情?还是使用未连接到数据库的连接对象?然后,我想将迁移结果临时写入文件中,以便以后进行处理.

Is there a way to use a cursor to do things like mogrify without an active connection object? Or with a connection object that is not connected to a database? I would then like to write the mogrify results temporarily to file so they can be processed later.

推荐答案

这将是一种脆弱的方法,因为该连接用于检测一些用于转义的参数(编码,符合标准的字符串等).

It would be a fragile approach, as the connection is used to detect some parameters used for escaping (encoding, standard-conforming string etc).

您可以对参数进行手动迁移"调用psycopg2.extensions.adapt(x).getquoted(),然后使用常规的Python %运算符将它们合并到查询中.

You can have a "manual mogrify" calling psycopg2.extensions.adapt(x).getquoted() on your parameters and then merging them to the query using the regular Python % operator.

当前发布的psycopg版本(最高2.3.2)可能会在None-> NULL转换时失败.您可以手动转换这些值,也可以为无注册适配器:您可以在此提交.

Currently released psycopg versions (up to 2.3.2) may fail on None -> NULL conversion though. You can either convert these values manually or register an adapter for None: you can see how in this commit.

这篇关于使用psycopg2构造无连接的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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