1
0

こちらのプログラムを改造して、csv の位置で、データをインポートします。
PostgreSQL: Python3 で csv をインポート

サンプルの csv

cities_jp.csv
識別記号,都市名,人口,更新日
t1271,千葉,73561,2019-7-30
t1272,勝浦,24895,2019-8-10
t1273,市原,67294,2019-1-14
t1274,流山,73612,2019-5-9
t1275,八千代,63491,2019-8-4
t1276,我孫子,41827,2019-1-21
t1277,鴨川,12946,2019-7-23
t1278,銚子,79128,2019-11-26
t1279,市川,13572,2019-10-15

プログラム

ポイントは、次です。

row.iloc[index]
csv_place_import.py
#! /usr/bin/python
#	csv_place_import.py
#
#						Jul/10/2024
# ------------------------------------------------------------------
import pandas as pd
import psycopg2
import sys
# ------------------------------------------------------------------
from prepare_sql import prepare_sql_proc
from prepare_sql import get_columns_order
# ------------------------------------------------------------------
csv_file = sys.argv[1]

dbname = "city"
user = "scott"
password = "tiger123"
host = "localhost"
port = "5432"

conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)

df = pd.read_csv(csv_file)

table_name = 'cities'

cur = conn.cursor()

array_columns = get_columns_order(cur,table_name)
sql = prepare_sql_proc(table_name,array_columns)
print(sql)

try:
	for index, row in df.iterrows():
		data = ()
		index = 0
		for col in array_columns:
			data += (row.iloc[index],)
			index += 1
		print(data)
 
		cur.execute(sql, data)
	
	conn.commit()
	print("データのインポートが完了しました。")

except psycopg2.Error as e:
	print(f"データのインポート中にエラーが発生しました: {e}")

finally:
	cur.close()
	conn.close()
# ------------------------------------------------------------------

prepare_sql.py はこちら
PostgreSQL: Python3 で csv をインポート

1
0
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
1
0