LoginSignup
0
1

CSVをMySQLに入れるPythonをChatGPTに書かせてみた

Last updated at Posted at 2023-08-06
import sys

import pandas as pd
import mysql.connector

from pathlib import Path

# MySQLデータベースへの接続情報
db_config = {
    'host': 'localhost',
    'user': 'username',
    'password': 'password',
    'database': 'database'
}

# CSVファイルをデータフレームに読み込む
p = Path(sys.argv[1])
df = pd.read_csv(p)

# MySQLデータベースに接続
db_connection = mysql.connector.connect(**db_config)
db_cursor = db_connection.cursor()

# テーブル名を指定
table_name = p.stem

# テーブルのカラム定義を生成
column_definitions = []
for column_name, dtype in zip(df.columns, df.dtypes):
    if dtype == 'int64':
        column_type = 'INT'
    elif dtype == 'float64':
        column_type = 'DOUBLE'
    else:
        column_type = 'VARCHAR(255)'  # 文字列型のデフォルト
    column_definitions.append(f'`{column_name}` {column_type}')

# テーブルを作成
create_table_query = f'''
    CREATE TABLE IF NOT EXISTS `{table_name}` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        {', '.join(column_definitions)}
    )
'''
# print(create_table_query)

db_cursor.execute(create_table_query)
db_connection.commit()

columns = [f"`{i}`" for i in df.columns]
insert_query = f'''
    INSERT INTO `{table_name}` ({', '.join(columns)})
    VALUES ({', '.join(['%s'] * len(columns))})
'''
# print(insert_query)

valuesList = []

# データをテーブルに挿入
for index, row in df.iterrows():
    values = [None if pd.isna(v) else v for v in row]
    valuesList.append(values)

db_cursor.executemany(insert_query, valuesList)
db_connection.commit()

# 接続を閉じる
db_cursor.close()
db_connection.close()

# print(p)

いくつか修正を入れています。

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