실제로 데이터베이스를 구현해 보도록 하겠습니다.
메모리에 SQLite3 데이터베이스를 만들고 4가지 속성을 지닌 sales 테이블을 만든다.
import sqlite3
conn = sqlite3.connect(':memory:')
query = """CREATE TABLE sales
product VARCHAR(20),
maker VARCHAR(40),
amount FLOAT,
date DATE);"""
conn.execute(query)
conn.commit()
sales 테이블에 데이터를 삽입한다.
data = [('smart phone', 'Apple', '47.2', '2019-08-03'),
('printer', 'Samsung', '15.2', '2018-02-10',),
('monitor', 'LG', '14.25', '2019-12-20'),
('python book', 'Amazon', '12.40', '2020-01-23')]
statement = "INSERT INTO sales VALUES(?, ?, ?, ?)"
conn.executemany(statement, data)
conn.commit()
sales 테이블에 질의한다.
cursor = conn.execute("SELECT * FROM sales")
rows = cursor.fetchall()
출력 데이터의 개수를 샌다.
row_counter = 0
for row in rows:
print(row)
row_counter += 1
print("Number of rows: {}".format(row_counter))
import sqlite3
conn = sqlite3.connect(':memory:')
query = """CREATE TABLE sales
(product VARCHAR(20),
maker VARCHAR(40),
amount FLOAT,
date DATE);"""
conn.execute(query)
conn.commit()
data = [('smart phone', 'Apple', '47.2', '2019-08-03'),
('printer', 'Samsung', '15.2', '2018-02-10',),
('monitor', 'LG', '14.25', '2019-12-20'),
('python book', 'Amazon', '12.40', '2020-01-23')]
statement = "INSERT INTO sales VALUES(?, ?, ?, ?)"
conn.executemany(statement, data)
conn.commit()
cursor = conn.execute("SELECT * FROM sales")
rows = cursor.fetchall()
row_counter = 0
for row in rows:
print(row)
row_counter +=1
print("Number of rows: {}".format(row_counter))
실행 결과