简体   繁体   English

在 Python 中的 psycopg2 中执行 .sql 模式

[英]Execute .sql schema in psycopg2 in Python

I have a PostgreSQL schema stored in .sql file.我有一个存储在 .sql 文件中的 PostgreSQL 模式。 It looks something like:它看起来像:

CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    facebook_id TEXT NOT NULL,
    name TEXT NOT NULL,
    access_token TEXT,
    created INTEGER NOT NULL
);

How shall I run this schema after connecting to the database?连接到数据库后如何运行此模式?

My existing Python code works for SQLite databases:我现有的 Python 代码适用于 SQLite 数据库:

# Create database connection
self.connection = sqlite3.connect("example.db")

# Run database schema
with self.connection as cursor:
    cursor.executescript(open("schema.sql", "r").read())

But the psycopg2 doesn't have an executescript method on the cursor.但psycopg2不具有executescript光标方法。 So, how can I achieve this?那么,我怎样才能做到这一点?

You can just use execute :你可以只使用execute

with self.connection as cursor:
    cursor.execute(open("schema.sql", "r").read())

though you may want to set psycopg2 to autocommit mode first so you can use the script's own transaction management.尽管您可能希望首先将 psycopg2 设置为autocommit模式,以便您可以使用脚本自己的事务管理。

It'd be nice if psycopg2 offered a smarter mode where it read the file in a statement-at-a-time and sent it to the DB, but at present there's no such mode as far as I know.如果 psycopg2 提供一种更智能的模式,它会在一次语句中读取文件并将其发送到数据库,那将会很好,但据我所知,目前没有这种模式。 It'd need a fairly solid parser to do it correctly when faced with $$ quoting (and its $delimiter$ variant where the deimiter may be any identifier), standard_conforming_strings , E'' strings, nested function bodies, etc.当面对$$引用(及其$delimiter$变体,其中$delimiter$可以是任何标识符)、 standard_conforming_stringsE''字符串、嵌套函数体等时,它需要一个相当可靠的解析器才能正确执行。

Note that this will not work with:请注意,这不适用于:

  • anything containing psql backslash commands任何包含psql反斜杠命令的内容
  • COPY .. FROM STDIN复制 .. 从标准输入
  • very long input长的输入

... and therefore won't work with dumps from pg_dump ...因此不适用于来自pg_dump转储

I can't reply to comments of the selected answer by lack of reputation, so i'll make an answer to help with the COPY issue.由于缺乏声誉,我无法回复所选答案的评论,因此我将回答以帮助解决COPY问题。

Depending on the volume of your DB, pg_dump --inserts outputs INSERT s instead of COPY s根据您的数据库的容量, pg_dump --inserts输出INSERT s 而不是COPY s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM