컴퓨터/Python
[Python] 파이썬, sqlite3 사용하기
sjblog
2023. 3. 23. 22:17
반응형
1. DB 저장
import sqlite3
import pandas as pd
con = sqlite3.connect('저장할 데이터베이스이름.db')
# 임의 데이터
data = {'col0':[0,1,2,3,4],'col1':[0,10,20,30,40]}
# 데이터프레임 생성
df = pd.DataFrame(data)
# 데이터프레임을 SQL로
df.to_sql('테이블이름', con, if_exists='append')
"""
옵션:
if_exists: SQL에 테이블이 이미 존재할 경우, fail, replace, append 중 선택 [기본값:fail]
index: index를 추가할지 [기본값:True]
등등
"""
2. DB 불러오기
con = sqlite3.connect('저장한 데이터베이스이름.db')
df1 = pd.read_sql('SELECT * FROM 테이블이름', con, index_col='index')
"""
옵션:
index_col: 인덱스로 설정한 컬럼 지정
"""
3. DB 테이블 불러오기
con = sqlite3.connect('저장한 데이터베이스이름.db')
cursor = con.cursor()
# 방법1
df = pd.read_sql("SELECT name FROM sqlite_master WHERE type='table';", con)
print(df)
# 방법2
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cur.fetchall())
4. DB 프로그램으로 확인하기
Downloads - DB Browser for SQLite
(Please consider sponsoring us on Patreon 😄) Windows Our latest release (3.12.2) for Windows: Windows PortableApp Note - If for any reason the standard Windows release does not work (e.g. gives an error), try a nightly build (below). Nightly builds ofte
sqlitebrowser.org
반응형