LoginSignup
0
1

More than 3 years have passed since last update.

投稿テスト5(psycopg2を使用したTable作成)

Posted at

技術メモ

# postgreSQLの接続情報
postgres_config = {
    'user': 'postgres',
    'pass': '123qwe!',
    'host': 'localhost',
    'port': '5432',
    'db':   'postgres'
}

# postgreSQLへ接続
config = ' user={user} dbname={db} password={pass}'.format(**postgres_config)

# with構文でclose()がいらない形で記述  
with psycopg2.connect(config) as conn:
    conn.autocommit = True  #commit()不要で実行できるよう設定
    with conn.cursor() as cur:
        # SQL文を実行
        cur.execute('SELECT * FROM hoge')

        # 実行結果の確認
        results = cur.fetchall()
        for r in results:
             print(r)

CSVからTableを作成するサンプルコード

import psycopg2
import csv
import os
import glob

# =============================================================================
# parameters
# =============================================================================

# テーブル定義CSVのファイルパス
DDL_DIRPATH = '/table定義/'

# postgreSQLの接続情報
postgres_config = {
    'user': 'postgres',
    'pass': '123qwe!',
    'host': 'localhost',
    'port': '5432',
    'db':   'postgres'
}

# =============================================================================
# function
# =============================================================================


# =============================================================================
# main
# =============================================================================

# テーブル定義CSVが入ったフォルダからCSVファイルのファイル名リストを作成
ddlfile = []
os.chdir(DDL_DIRPATH)
ddlfile.extend(glob.glob('*.csv'))

# 1テーブル定義CSVにつき、1テーブルを新規作成
for i in ddlfile:
    print(i)

    csv_file = open("/Users/KODAI/Desktop/table定義/"+i, "r", encoding="ms932", errors="", newline="" )
    ddl_file = csv.reader(csv_file, delimiter=",", doublequote=True, lineterminator="\r\n", quotechar='"', skipinitialspace=True)


    # テーブル名を取ってくるところは既存コードを流用する ※編集
    head = next(ddl_file)
    print(head)
    table_name = head[1]

    next(ddl_file)
    next(ddl_file)

    ### CREATE TABLE 文を作成開始
    sql_create_table='CREATE TABLE '+table_name+' ('

    # CSVファイルから各カラムの設定を記述
    for row in ddl_file:
        # CSVに短縮して書かれている定義は、正しい型名に修正する
        if row[1]=='DOUBLE':
            row[1] = 'DOUBLE PRECISION'
        # 各カラムの定義作成
        sql_create_table += '\"' + row[0] +'\"' + ' ' +row[1] + ','

    # 末尾のカンマを削除して、括弧を閉じる
    sql_create_table = sql_create_table[:-1]
    sql_create_table += ')'
    ### CREATE TABLE 文を作成完了

    # postgreSQLへ接続
    config = ' user={user} dbname={db} password={pass}'.format(**postgres_config)

    # with構文でclose()がいらない形で記述  
    with psycopg2.connect(config) as conn:
        conn.autocommit = True  #commit()不要で実行できるよう設定
        with conn.cursor() as cur:
            # 作成したCREATE TABLE 文を実行
            cur.execute(sql_create_table)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1