From 5de39f92a4040955b9105cd291820d5d6fac8446 Mon Sep 17 00:00:00 2001 From: suti7yk5032 Date: Sun, 7 Jul 2024 13:50:57 +0900 Subject: [PATCH] =?UTF-8?q?PC=E4=BD=BF=E7=94=A8=E5=B1=A5=E6=AD=B4=E3=81=AE?= =?UTF-8?q?=E3=83=86=E3=83=BC=E3=83=96=E3=83=AB=E3=81=8B=E3=82=89csv?= =?UTF-8?q?=E3=83=95=E3=82=A1=E3=82=A4=E3=83=AB=E3=82=92=E4=BD=9C=E6=88=90?= =?UTF-8?q?=E3=81=A7=E3=81=8D=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- temp/csv.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 temp/csv.py diff --git a/temp/csv.py b/temp/csv.py new file mode 100644 index 0000000..6a8dd24 --- /dev/null +++ b/temp/csv.py @@ -0,0 +1,69 @@ +import psycopg2 +import csv +from psycopg2 import sql +from datetime import datetime + +def format_datetime(value): + if isinstance(value, datetime): + return value.strftime('%Y-%m-%d %H:%M:%S') + return value + +def export_table_to_csv(host, port, database, user, password, table_name, csv_file_path): + try: + # データベースに接続 + conn = psycopg2.connect( + host=host, + port=port, + database=database, + user=user, + password=password + ) + + # カーソルを作成 + cur = conn.cursor() + + # テーブルの全データを取得 + cur.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier(table_name))) + + # 列名を取得 + column_names = [desc[0] for desc in cur.description] + + # 結果を取得 + rows = cur.fetchall() + + # CSVファイルに書き込み + with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile: + csvwriter = csv.writer(csvfile) + + # 列名を書き込み + csvwriter.writerow(column_names) + + # データを書き込み + for row in rows: + # 各フィールドを適切にフォーマット + formatted_row = [format_datetime(field) if field is not None else '' for field in row] + csvwriter.writerow(formatted_row) + + print(f"テーブル '{table_name}' の内容を '{csv_file_path}' に出力しました。") + + except (Exception, psycopg2.Error) as error: + print("エラーが発生しました:", error) + + finally: + # データベース接続を閉じる + if conn: + cur.close() + conn.close() + print("データベース接続を閉じました。") + +# 使用例 +# 使用例 +host = "192.168.1.220" +port = "12245" +database = "dislocker" +user = "suti7" +password = "Testing1234" +table_name = "pc_usage_history" +csv_file_path = "./output.csv" + +export_table_to_csv(host, port, database, user, password, table_name, csv_file_path)