简体   繁体   English

如何通过 Python 在 PostGreSQL 中插入列注释?

[英]How can I insert column comments in PostGreSQL via Python?

Problem问题

I want to add a comment to a number of columns from Python in a PostGreSQL database.我想向 PostGreSQL 数据库中 Python 的许多列添加注释。 If I run the statement that my Python script produces in a database client manually everything works as it should.如果我手动运行 Python 脚本在数据库客户端中生成的语句,则一切正常。 If I let Python run the statement via an sqlalchemy engine, nothing is updated.如果我让 Python 通过 sqlalchemy 引擎运行语句,则不会更新任何内容。

Details细节

I have a dictionary in Python of the form { 'column name': 'column comment with some text'} .我有一个 Python 字典,格式为{ 'column name': 'column comment with some text'}

I want to add this comments to an existing table in a PostGres database.我想将此注释添加到 PostGres 数据库中的现有表中。

Manually I would run the following command in PostGres:我会手动在 PostGres 中运行以下命令:

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

Now in Python I want to run the same, but then looping over the dictionary.现在在 Python 中我想运行相同的,但然后循环字典。 This is the code I use:这是我使用的代码:

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))

This prints out:这打印出来:

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.';

When I check the column comments with the query from this answer no comments are actually set.当我使用此答案中的查询检查列注释时,实际上并未设置任何注释。

If I copy-paste what is printed out into a database client and run it there, the column comment is updated as it should.如果我将打印出来的内容复制粘贴到数据库客户端并在那里运行,则列注释会按原样更新。

How can I update the column comment via a loop in Python?如何通过 Python 中的循环更新列注释?

You did not commit your changes, so they are automatically rolled back.您没有提交更改,因此它们会自动回滚。 One way to do it is:一种方法是:

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

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

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