본문 바로가기

프로그래밍/Python

[요약] 파이썬(Python) SQLite DB 연동

[요약] 파이썬(Python) SQLite DB 연동


파이썬으로 SQLite DB에 대해 다음 작업을 할 수 있다.

  • SQLite DB 생성
  • SQLite 패키지 버전 알아내기 : sqlite3.version
  • SQLite DB 버전 알아내기 : sqlite3.sqlite_version
  • 날짜 포멧 출력 : datetimeVar.strftime('%Y-%m-%d %H:%M:%S')
  • SQLLite 연결 및 데이터베이스 생성 : sqlite3.connect
  • 커서 얻기 : conn.cursor()
  • SQL명령 실행 : cursor.execute
  • 튜플을 이용한 대량 데이터 삽입(Bulk Insert, Many Insert) : cursor.executemany
  • 커밋, 롤백
  • SQLite 관리를 위한 DB Browser Tool 설치


# 파이썬 데이터베이스 연동(SQLite)

import sqlite3 # 기본 패키지로 포함되어 있음

# sqllite3 - 버전정보 얻기
print('sqlite3.version : ', sqlite3.version)                # sqlite3.version :  2.6.0
print('sqllte3.sqlite_version : ', sqlite3.sqlite_version)  # sqllte3.sqlite_version :  3.31.1

# 날짜 생성
import datetime
now = datetime.datetime.now()
print('now : ', now)                    # now :  2020-12-07 10:42:37.849037

nowDateTime = now.strftime('%Y-%m-%d %H:%M:%S')
print('nowDateTime : ', nowDateTime)    # nowDateTime : 2020-12-07 10:43:29


# DB생성 및 Auto Commit, RollBack
conn = sqlite3.connect('D:/Python_Basic/resource/database.db', isolation_level=None) # 해당 경로에 database.db DB파일이 생성된다.

# 커서(Cursor)의 이용
cursor = conn.cursor()
print('Cursor Tppe : ', type(cursor))    # Cursor Tppe :  

# 테이블 생성(Data Type : TEXT, NUMERIC INTEGER, REAL, BLOB)
cursor.execute('CREATE TABLE IF NOT EXISTS users(id integer primary key, username text, \
    email text, phone text, website text, regdate)')

# SQLite 데이터 삽입
# 직접쓰기
cursor.execute('insert into users values (1, "Lee", "honggildong@gmail.com","lee.com", "000-0000-0001", ?)', (nowDateTime,))
# 파라미터 이용하기
cursor.execute("insert into users (id, username, email, phone, website, regdate) values (?,?,?,?,?,?)", (2, 'Park', 'lee@xxx.com', '000-0000-0002', 'http://localhost', nowDateTime))


# Insert (Many Insert) 대량데이터 삽입 (튜플, 리스트)
userList = (
        (3, 'Lee', 'Lee@dacom.com', '010-0000-0003', 'lee2@com', nowDateTime),
        (4, 'Kim', 'Kim@dacom.com', '010-0000-0004', 'Kim@com', nowDateTime),
        (5, 'Jang', 'Jang@dacom.com', '010-0000-0005', 'Jang@com', nowDateTime)
)

cursor.executemany("insert into users(id, username, email, phone, website, regdate) values (?,?,?,?,?,?)", userList)

# 테이블 데이터 전체 삭제
# cursor.execute("delete from users")
# 데이터를 지우고 지운 건수를 확인하는 방법
# print("users db deleted : ", conn.execute('delete from users').rowcount)    # users db deleted :  5

# 커밋 : isolation_level = None일 경우는 쿼리 실행과 동시에 반영(오토 커밋)
# conn.commit()  직접 현재 시점에서 수동으로 커밋

# 롤백
# conn.rollback()

# 접속해제
conn.close()