import sqlite3
conn = sqlite3.connect('student.db')
# SQL문
# name(이름), no(번호), addr(주소), gender(성별)
sql = """
CREATE TABLE student
(
name text,
no integer,
addr text,
gender text
)
"""
# 테이블 생성하기
c = conn.cursor() # Connetion 객체를 이용하여 cursor를 만든다.
c.execute("DROP TABLE IF EXISTS student") # student가 있으면 삭제해라.
c.execute(sql) # 테이블 생성.
c.close()
sql = """
INSERT INTO student VALUES
('학생1', 1, "서울 강남구 일원동", 'male')
"""
c = conn.cursor() # 객체 생성
c.execute(sql)
c.close()
conn.commit()
sql = 'select * from student'
c = conn.cursor()
c.execute(sql)
# 하나의 데이터
print(c.fetchone())
('학생1', 1, '서울 강남구 일원동', 'male')
sql = """
INSERT INTO student VALUES
(?, ?, ?, ?)
"""
c = conn.cursor() # 객체 생성
c.execute(sql, ('학생2', 2, '안양', 'female'))
data = [
('학생3', 3, '경기도', 'female'),
('학생4', 4, '춘천', 'female'),
('학생5', 5, '대구', 'male')
]
c.executemany(sql, data)
c.close()
conn.commit()
sql = 'select * from student'
c = conn.cursor()
c.execute(sql)
for s in c.fetchmany(10):
print(s)
('학생1', 1, '서울 강남구 일원동', 'male') ('학생2', 2, '안양', 'female') ('학생3', 3, '경기도', 'female') ('학생4', 4, '춘천', 'female') ('학생5', 5, '대구', 'male')