Python を使用して postgres データベース フィールドの長さと型をバッチで自動的に変更し、主キーを追加します

テーブルの構造が標準的ではないため、フィールドの長さが長すぎる、型が一致しないなどの理由で、後からデータを保存する際にエラーが発生するため、確認・修正が必要です。テーブルを 1 つずつ作成するのは大変な作業です。

修正には半日かかりましたが、修正後は目がかすみ、手足に力が入らなくなり、本当に涙が出ました!

作業負荷を軽減し、手を解放して携帯電話を操作できるようにするには、このようなことをプログラムに任せるのが良いでしょう。

まあ、おいしいですよ。

ただやってください、やってください

(ここに区切り線があります)

1. ステップの内訳

1. データベースに接続する

import psycopg2

conn=psycopg2.connect(database='database',user='username',password='password',host='ip地址',port='5432')
cursor=conn.cursor()

2. データベース内のすべてのテーブル名をクエリします。

cursor.execute("select tablename  from pg_tables where schemaname='public';")
table_name=cursor.fetchall()

3. 単一テーブルのデータを確認するには、次のステートメントで table_name を特定のテーブルの名前に置き換える必要があります。

select a.attnum,a.attname,concat_ws('',t.typname,SUBSTRING(format_type(a.atttypid,a.atttypmod) from '\(.*\)')) as type,d.description from pg_class c, pg_attribute a , pg_type t, pg_description d 
where  c.relname = 'table_name' and a.attnum>0 and a.attrelid = c.oid and a.atttypid = t.oid and  d.objoid=a.attrelid and d.objsubid=a.attnum
或(建议用下面这条)
select a.attnum,a.attname,case when a.attlen > 0 then a.attlen else a.atttypmod - 4 end as type,d.description from pg_class c, pg_attribute a , pg_type t, pg_description d 
where  c.relname = 'gn_cl_gnqcjrczxx' and a.attnum>0 and a.attrelid = c.oid and a.atttypid = t.oid and  d.objoid=a.attrelid and d.objsubid=a.attnum

4. フィールド長を 255 に変更します。

cursor.execute("ALTER TABLE table_name alter COLUMN column_name type  varchar(255);")

5.フィールドタイプをテキストタイプに変更します

cursor.execute("ALTER TABLE  table_name alter COLUMN column_name type text;")

6.主キーの追加

ALTER TABLE table_name ADD primary key(id);

2. 完全なコード

エネルギーが高い前方、ズームイン

複数のテーブルがあるため、プログラムを 1 つずつ入力する必要がありますが、これは十分スマートではありません。for ループを使用してテーブル クエリを解決でき、フィールド クエリも同じです。長さが 255 未満のフィールド。

データをデータベースに保存した後、フィールド長が 255 より大きい場合、255 に戻すとエラーが報告されることがあります。この問題を解決するには、try...以外を使用してください。

次に完全なプログラムを出力します。

import psycopg2

conn=psycopg2.connect(database='my_database',user='postgres',password='postgres',host='ip',port='5432')
cursor=conn.cursor()

#查出数据库中所有表名称
cursor.execute("select tablename  from pg_tables where schemaname='public';")
table_name=cursor.fetchall()


for i in range(len(table_name)):
    #查出表的所有字段长度和注释
    cursor.execute("select a.attnum,a.attname,case when a.attlen > 0 then a.attlen else a.atttypmod - 4 end as type,d.description \
                   from pg_class c, pg_attribute a , pg_type t, pg_description d where  c.relname = '%s' and a.attnum>0 \
                   and a.attrelid = c.oid and a.atttypid = t.oid and  d.objoid=a.attrelid and d.objsubid=a.attnum"%table_name[i])
    column_name=cursor.fetchall()
    
    for j in range(len(column_name)):
        if int(column_name[j][0])>255:
            try:
                #修改字段长度为255
                cursor.execute("ALTER TABLE %s1 alter COLUMN %s2 type  varchar(255);"%(table_name[i],column_name[j]))
            except:
                #修改字段类型为text类型
                cursor.execute("ALTER TABLE  %s1 alter COLUMN %s2 type text;"%(table_name[i],column_name[j]))
    conn.commit()
cursor.close()
conn.close() 

どのフィールドを具体的に変更したい場合は、リスト テーブルを作成して try のステートメントを保存すると、何を実行するかを知ることができます。結局のところ、プログラムを使用してこれらを実行することには大きなリスクが伴います。

注意: このプログラムには危険が伴いますので、使用には注意してください。

おすすめ

転載: blog.csdn.net/quantam/article/details/110521593