본문 바로가기
etc

[DB] SQL with python

by wycho 2022. 5. 31.

Python에서 db 파일을 불러오거나 생성하여 데이터를 처리해 보자.

import sqlite3

con = sqlite3.connect('test.db')
cur = con.cursor()
  • sqlite3 패키지는 python3에 기본으로 내장되어 있다.
  • 우선 DB에 접근하기 위해 파일을 연결시켜야 한다.
  • cursor를 불러와 DB에 접근한다. 
cur.execute("CREATE TABLE IF NOT EXITS product (date text, item text, state text, ea real)")

cur.execute("INSERT INTO product VALUES ('2022-05-30','CPU','SOLD',100)")

product_list = [('2022-05-30','RAM','KEEP',300), ('2022-05-31','POWER','SOLD',200)]

cur.executemany("INSERT INTO product VALUES (?,?,?), product_list")

con.commit()
  • SQL은 영어를 사용하는 것과 같은 방식의 문법을 사용하고 있다. 명령어는 execute 로 실행시킨다. 참고로 python은 대소문자 구분이 없다.
  • CREATE 를 통해 표를 생성한다. 각 항목이 어떤 데이터 타입을 갖는지 설정해준다. 데이터 타입은 NULL, INTEGER, REAL, TEXT, BLOB (input 그대로의 형식) 의 5개가 있다.
  • INSERT 로 row 데이터를 넣는다.
  • commit 을 실행하여 DB에 저장한다.
cur.execute("SELECT * FROM product")
# or
cur.execute("SELECT * FROM product WHERE trans == 'KEEP' ORDER BY price")

print(cur.execute("SELECT * FROM product"))
<sqlite3.Cursor object at 0x7f59848c3dc0>

rows = cur.fetchall() # gives a whole list of data in the table
  • 조건에 맞는 데이터를 선택한다.
cols = cols = list(map(lambda x: x[0], cur.description))
df = pd.DataFrame.from_records(data=rows, columns=cols)
  • pandas 표로 만들 경우.
con.close()
  • DB 를 더 이상 사용하지 않을 때 닫아준다.

 

 

 

 

 

'etc' 카테고리의 다른 글

[Excel] 하이퍼링크, 시트정렬  (0) 2022.09.14
pathlib in python  (0) 2022.08.18
Markdown guide  (0) 2022.03.09
Common ancestor  (0) 2022.01.24
Read table data with Parquet  (0) 2021.10.18

댓글