pandas 를 이용해서 xlst 을 sqldb 로 전달하기
music_pandas_xls2sql.py
#coding : utf-8
import pandas as pd
import sqlite3
import sys
def connect_db(dbname):
conn = sqlite3.connect(dbname)
return conn
def insert_with_pd (conn, infilename):
try:
df = pd.read_excel (infilename)
from pathlib import Path
tablename = Path (infilename).stem # 'music/Albums.xlsx' -> Albums
df.to_sql(tablename, conn) # this does 'creating table and inserting
except Exception as e:
print(e, file=sys.stderr)
return
if __name__=='__main__':
try:
conn=connect_db( 'music/musicDB.sqlite3')
insert_with_pd(conn, 'music/Albums.xlsx')
insert_with_pd(conn, 'music/Kpop_release.xlsx')
conn.close()
except Exception as e:
print(e)
1. .sqlite3 db 를 연결한다.
2. 주어진 매개변수들로 엑셀 파일을 읽는다.
3. 테이블의 이름은 . 기준 파일 명이 된다.
4. 엑셀 파일을 읽고 이를 sqlite 에 데이터로 저장한다. (df.to_sql)
music_pandas_xls2sql.py 조금 더 개선한 것
#coding : utf-8
import pandas as pd
import sqlite3
import sys
def connect_db(dbname):
conn = sqlite3.connect(dbname)
return conn
def insert_with_pd2(conn, infilename):
try:
Efile = pd.ExcelFile(infilename)
from pathlib import Path
pre = Path(infilename).stem # 'music/Albums.xlsx' -> Albums
sh_names=Efile.sheet_names
tablename = pre + '>' + sh_name
print(tablename)
df = pd.read_excel(Efile, sh_name)
df.to_sql(tablename, conn)
except Exception as e:
print(e, file=sys.stderr)
return
if __name__=='__main__':
try:
conn=connect_db( 'music/musicDB.sqlite3')
insert_with_pd2(conn, 'music/Albums.xlsx')
insert_with_pd2(conn, 'music/Kpop_release.xlsx')
conn.close()
except Exception as e:
print(e)
~
엑셀의 아래 sheet name 을 sh_names = Efile.sheet_names 로 가져오기
그리고 각 sh_name 에 따라 테이블 이름 설장해두고 sheet 의 데이터 읽어서 sqlite 에 넣어주기
결과는 다음과 같다
(Albums 에는 Love youself Tear 시트 하나)
(Kpop_release 엔 3 시트)
'수업정리 > Fundamental' 카테고리의 다른 글
[Python] 한글 유니코드 9 - urllib.py, scrape_wiki_random.py, 위키에서 읽고 데이터 받기? (0) | 2023.06.07 |
---|---|
[Python] 한글 유니코드 9 - 질의처리(select, from, where), 쿼리문 파이썬 파일만들기 (0) | 2023.06.02 |
[Python] 한글 유니코드 7 - sqlite3, index, gdown 파일 연결하기, pandas, openpyxl (0) | 2023.05.26 |
[Python] 한글 유니코드 6 - sqlite3, test_sqldb.py (0) | 2023.05.24 |
[Python] 한글 유니코드 5 - 한글 decompose 해서 모음,자음 넣기 (0) | 2023.05.19 |