w1_sqlite3 - steelbear/HMG_Softeer_DE GitHub Wiki

SQLite란?

  • 가볍고 빠르며 애플리케이션에 통합시킬 수 있는 RDB
  • DB를 가동시키기 위해 따로 DB 서버를 킬 필요는 없다

sqlite3이란?

  • python에서 SQLite를 사용할 수 있도록 도와주는 라이브러리
    • 내장 라이브러리라 따로 설치할 필요는 없다
  • PEP 249를 만족
    • 다른 데이터베이스와 동일한 방식으로 접근할 수 있다

SQLite에 접속하기

conn = None
try:
    conn = sqlite3.connect(filename) # 데이터베이스 접속
    print(sqlite3.sqlite_version)
except sqlite3.Error as e:
    print(type(e))
    print('Err:', e)
finally:
    if conn:
        conn.close() # 연결 종료

쿼리 전달하기

cur = conn.Cursor()

# 단일 쿼리 실행
cur.execute('SELECT * FROM Customers;')

# 매개변수를 통한 쿼리 실행
cur.execute('INSERT INTO Products (ProductName, UnitPrice) VALUES (?, ?)',
            ('Just Soup', '5000'))
# 동일한 쿼리 반복 실행
cur.executemany('INSERT INTO Products (ProductName, UnitPrice) VALUES (?, ?)',
                [('Apple', '100'), ('Banana', '200')])

# 여러줄의 SQL 코드 실행
cur.executescript('''
                  CREATE TABLE IF NOT EXISTS Products (
                      -- ...
                  );
                  
                  SELECT * FROM Products;
                  ''')

conn.commit() # 변경사항 모두 저장

쿼리 실행 결과 보기

for row in cur.fetchall():
    print(row)

# Cursor를 통해 실행 결과 보기
data = cur.execute('...')

columns = list(map(lambda x: x[0], data.description))
print(columns)

for row in cur:
    print(cur)