SQLite3는 가볍고 독립적이며 서버가 필요 없는 SQL 데이터베이스 엔진이다. Python의 sqlite3 모듈은 SQLite 데이터베이스와 상호작용할 수 있는 간단한 인터페이스를 제공한다.
sqlite3.connect()를 사용하여 SQLite 데이터베이스에 연결한다. 데이터베이스 파일이 없으면 자동으로 생성됩니다.import sqlite3
# SQLite 데이터베이스에 연결 (또는 생성)
connection = sqlite3.connect("example.db")
print("데이터베이스에 성공적으로 연결되었습니다!")
# 연결 종료
connection.close()
SQL CREATE TABLE 명령문을 사용하여 테이블을 생성한다.
커서(cursor) 객체를 사용하여 SQL 명령을 실행한다.
# 데이터베이스에 연결
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
## 테이블 생성
SQL CREATE TABLE 명령문을 사용하여 테이블을 생성한다.
커서(cursor) 객체를 사용하여 SQL 명령을 실행한다.
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
""")
print("테이블이 성공적으로 생성되었습니다!")
# 변경 사항 저장 및 연결 종료
connection.commit()
connection.close()
INSERT INTO 명령문을 사용하여 테이블에 레코드를 추가합니다.
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
# 데이터베이스에 연결
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", ("Alice", 20, "A"))
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", ("Bob", 22, "B"))
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", ("Charlie", 21, "C"))
print("데이터가 성공적으로 삽입되었습니다!")
# 변경 사항 저장 및 연결 종료
connection.commit()
connection.close()
SELECT 명령문을 사용하여 테이블에서 데이터를 조회합니다.
# 데이터베이스에 연결
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
# 데이터 조회
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
# 데이터 출력
print("학생 레코드:")
for row in rows:
print(row)
# 연결 종료
connection.close()
UPDATE와 DELETE 명령문을 사용하여 레코드를 수정하거나 삭제합니다.
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
# 레코드 수정
cursor.execute("UPDATE students SET grade = ? WHERE name = ?", ("A+", "Bob"))
print("레코드가 성공적으로 수정되었습니다!")
# 레코드 삭제
cursor.execute("DELETE FROM students WHERE name = ?", ("Charlie",))
print("레코드가 성공적으로 삭제되었습니다!")
# 변경 사항 저장 및 연결 종료
connection.commit()
connection.close()
? 플레이스홀더와 매개변수를 사용하여 SQL 인젝션 취약성을 방지합니다.
# 데이터베이스에 연결
connection = sqlite3.connect("example.db")
cursor = connection.cursor()
# 안전한 쿼리 예
name = "Alice"
cursor.execute("SELECT * FROM students WHERE name = ?", (name,))
result = cursor.fetchone()
print("쿼리 결과:")
print(result)
# 연결 종료
connection.close()
학생 레코드를 관리하는 간단한 인터랙티브 프로그램을 만듭니다.
def create_database():
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
""")
connection.commit()
connection.close()
def add_student(name, age, grade):
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", (name, age, grade))
connection.commit()
connection.close()
def view_students():
connection = sqlite3.connect("student.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
connection.close()
return rows
# 데이터베이스 및 테이블 생성
create_database()
# 학생 추가
add_student("Alice", 20, "A")
add_student("Bob", 22, "B")
# 학생 목록 출력
students = view_students()
print("학생 레코드:")
for student in students:
print(student)