[CV 프로그램 만들기] 7. SQLite3 사용법

hostOS에서 프로그램 작성시에 사용될 수 있는 sqlite3의 코드 예제입니다.

 

무거운 데이터 베이스 프로그램을 사용하지 않고,

 

가볍게 데이터를 저장하거나 모바일 등에서 데이터베이스를 사용하려면 SQLite3를 사용하는 것이 좋습니다.

 

데이터 입력 예제

import sqlite3

conn = sqlite3.connect("samsongDB")  # 1. DB 연결
cur = conn.cursor() # 2. 커서 생성 (트럭, 연결로프)
sql = "CREATE TABLE IF NOT EXISTS userTable(userId INT, userName CHAR(5))"
cur.execute(sql)

sql = "INSERT INTO userTable VALUES( 1 , '홍길동')";
cur.execute(sql)
sql = "INSERT INTO userTable VALUES( 2 , '이순신')";
cur.execute(sql)

cur.close()
conn.commit()
conn.close() # 6. DB 닫기 (=연결 해제)
print('OK~')

 

데이터 가져오기 예제

import sqlite3

conn = sqlite3.connect("samsongDB")  # 1. DB 연결
cur = conn.cursor() # 2. 커서 생성 (트럭, 연결로프)
sql = "SELECT * FROM userTable"
cur.execute(sql)

rows = cur.fetchall()

print(rows)


cur.close()
conn.close() # 6. DB 닫기 (=연결 해제)
print('OK~')

 

댓글

Designed by JB FACTORY