【问题标题】:How can I insert column comments in PostgreSQL via Python?如何通过 Python 在 PostgreSQL 中插入列注释?
【发布时间】:2020-02-13 14:58:25
【问题描述】:

问题

我想为 PostgreSQL 数据库中的 Python 的许多列添加注释。 如果我手动运行我的 Python 脚本在数据库客户端中生成的语句,那么一切都会正常运行。 如果我让 Python 通过 sqlalchemy 引擎运行语句,则不会更新任何内容。

详情

我有一个{ 'column name': 'column comment with some text'} 形式的 Python 字典。

我想将此 cmets 添加到 Postgres 数据库中的现有表中。

我会在 Postgres 中手动运行以下命令:

comment on column schema.table."column name" is 'column comment with some text'

现在在 Python 中,我想运行相同的程序,然后循环遍历字典。这是我使用的代码:

from sqlalchemy import create_engine, text

db = create_engine(f"postgresql://PGUSER:PGPASSWORD@PGHOST/PGDATABASE")

coldict = {'col1': 'col1 contains this data, etc... some more comments', 'col2': 'col2 shows something.'}

with db.connect() as con:
        for key in coldict:
            colname = key
            # Convert a single quote to two single quotes as that is what SQL likes.
            colcomm = coldict[key].translate(str.maketrans({"'": "''"}))
            stmt = f"comment on column schema.table.\"{colname}\" is '{colcomm}';"
            # print the statement that will be run for debugging
            print(stmt)
            # execute statement in database
            con.execute(text(stmt))

打印出来:

comment on column schema.table."col1" is 'col1 contains this data, etc... some more comments';
comment on column schema.table."col2" is 'col2 shows something.';

当我使用来自this answer 的查询检查列 cmets 时,实际上没有设置任何 cmets。

如果我将打印出来的内容复制粘贴到数据库客户端并在那里运行,列注释会按应有的方式更新。

如何在 Python 中通过循环更新列注释?

【问题讨论】:

标签: python postgresql sqlalchemy


【解决方案1】:

您没有提交更改,因此它们会自动回滚。一种方法是:

con.execute(text(stmt).execution_options(autocommit=True))

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 2017-07-02
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多