Skip to content

Instantly share code, notes, and snippets.

@salamcast
Last active April 7, 2025 20:05
Show Gist options
  • Save salamcast/8923bfa5bd9178090d20b8d27e42307c to your computer and use it in GitHub Desktop.
Save salamcast/8923bfa5bd9178090d20b8d27e42307c to your computer and use it in GitHub Desktop.
import csv to MySQL
"""
uv project toml
---------------
[project]
name = "mysql_csv_import"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"pandas>=2.2.3",
"pathlib>=1.0.1",
"pymysql>=1.1.1",
"sqlalchemy>=2.0.40",
]
-------------
"""
import glob
import pandas as pd
from pathlib import Path
from sqlalchemy import create_engine, types
user='root'
passwd='toor'
host='localhost'
dbname='mydb'
engine = create_engine('mysql+pymysql://' + user + ':' + passwd + '@' + host + '/' + dbname)
for x in glob.glob('csv/*.csv'):
print(x)
df = pd.read_csv(x,sep=',',quotechar='\"',encoding='utf8')
#print(Path(x).stem)
#print(df)
#CSV filename for table
df.to_sql(Path(x).stem,con=engine,index=False,if_exists='append')
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment