본문 바로가기
카테고리 없음

파이썬으로 SQLite DB 사용하기 (초보편)

by python pro 2023. 2. 3.
반응형

Python SQLite는 SQLite 데이터베이스를 Python 언어로 제어할 수 있는 라이브러리입니다. SQLite는 관계형 데이터베이스를 지원하며, 파일 기반의 데이터베이스로 간단하게 사용할 수 있습니다.

 

설치하는 방법

$ pip install sqlite3

 

데이터베이스 연결하는 방법

import sqlite3

connection = sqlite3.connect("mydatabase.db")

 

테이블 생성하는 방법

cursor = connection.cursor()
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
connection.commit()

 

데이터 삽입하는 방법

cursor.execute("INSERT INTO users (name, age) VALUES ('John', 25)")
connection.commit()

 

데이터 조회하는 방법

cursor.execute("SELECT * FROM users")
print(cursor.fetchall())

 

데이터베이스 연결 종료하는 방법

connection.close()

 

SQLite를 사용하여 간단한 사용자 정보를 관리하는 예를 들어보겠습니다.

import sqlite3

def create_table():
    connection = sqlite3.connect("users.db")
    cursor = connection.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
    connection.commit()
    connection.close()

def add_user(name, age):
    connection = sqlite3.connect("users.db")
    cursor = connection.cursor()

    cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
    connection.commit()
    connection.close()

def get_all_users():
    connection = sqlite3.connect("users.db")
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users")
    users = cursor.fetchall()
    connection.close()
    return users

create_table()
add_user("John", 25)
add_user("Mary", 30)
print(get_all_users())

위 코드는 SQLite를 사용하여 사용자 정보를 관리하는 예시입니다.

create_table() 함수는 users 테이블을 생성하고,

add_user(name, age) 함수는 사용자 정보를 삽입하며,

get_all_users() 함수는 모든 사용자 정보를 조회합니다.

 

 

잘못된 코드 예시는 아래와 같습니다.

import sqlite3

connection = sqlite3.connect("users.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")

위 코드는 함수를 사용하지 않고 직접 연결, 커서를 생성하는 것이기 때문에, 코드를 실행할 때마다 새로운 연결을 생성하여 메모리를 많이 사용하게 됩니다. 그리고 프로그램이 종료되었을 때도 커넥션이 닫히지 않아 메모리를 잡아먹게 됩니다. 따라서, Python SQLite를 사용할 때는 항상 함수를 사용하여 연결과 커서를 생성하고, 사용이 끝나면 반드시 close()를 호출하여 연결을 종료하는 것이 좋습니다.

 

SQLite는 성능이 떨어지는 경우가 있으니 큰 데이터를 관리하는 시스템을 구축할 때는 다른 데이터베이스 시스템을 사용하는 것이 좋습니다.

 

 

반응형

댓글