import sqlite3 # built-in library (Python 2.x & 3.x)
dbpath = "chinook.db"
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
script = """
DROP TABLE IF EXISTS employees;
CREATE TABLE employees(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
salary REAL,
department TEXT,
position TEXT,
hireDate TEXT);
INSERT INTO employees(name, salary, department, position, hireDate) VALUES('Dave', 300, 'Marketing', 'LV1', '2020-01-01');
INSERT INTO employees(name, salary, department, position, hireDate) VALUES('Clara', 420, 'Sales', 'LV2', '2018-01-11');
INSERT INTO employees(id, name, salary, department, position, hireDate) VALUES(3, 'Jane', 620, 'Developer', 'LV4', '2015-11-01');
INSERT INTO employees VALUES(4, 'Peter', 530, 'Developer', 'LV2', '2020-11-01');
"""
cur.executescript(script)
conn.commit() # 실제로 DB에 위 Table & Data가 저장된다.
execute(sql[, parameters])
executemany(sql[, parameters])
executescript(sql_script)
예)
data = [('Elena', 510, 'Recruiter', 'LV3', '2020-07-01'),
('Sujan', 710, 'HR', 'LV5', '2014-06-01'),
('Jake', 210, 'CEO', 'LV8', '2012-01-01')]
cur.executemany("INSERT INTO employees(name, salary, department, position, hireDate)
VALUES(?, ?, ?, ?, ?)", data)
conn.commit()
- fetchall() 모든 데이타를 한꺼번에 클라이언트로 가져올 때 사용된다.
- fetchone() 한번 호출에 하나의 Row 만을 가져올 때 사용된다.
- fetchmany(n) n개 만큼의 데이타를 한꺼번에 가져올 때 사용된다.
예)
cur.execute("SELECT * FROM employees;")
employee_list = cur.fetchall()
for employee in employee_list:
print(employee)
import pandas as pd
df = pd.read_sql_query("SELECT * FROM employees", conn)
conn.close()
script = """
INSERT INTO artists (name)
VALUES
("Buddy Rich"),
("Candido"),
("Charlie Byrd");
"""
cur.execute(script)
script = """
SELECT
ArtistId,
Name
FROM
Artists
ORDER BY
ArtistId DESC;
"""
cur.execute(script)
df = pd.read_sql_query(script, conn)
df.head()
for li in boxItems:
title = li.find_element_by_class_name('proTit').text # li.find_element_by_css_selector('h5.proTit').text
price = li.find_element_by_class_name('proPrice').text.replace(',','').replace('원~','') # li.find_element_by_css_selector('.proPrice')
image = li.find_element_by_class_name('img').get_attribute('src')
sql_query = "INSERT INTO tour_crawl(title, price, image) values('{}',{},'{}')".format(title, price, image) # TEXT인 제목은 ''로 감싸주는 것에 유의
print('SQL Query :', sql_query[:90], "...")
cur.execute(sql_query)
conn.commit()
이상으로 Python 에서 SQL을 다루는 방법에 대한 설명을 마치도록 하겠습니다.
감사합니다.
더 나은 개발이 되길 바라며:)