In [8]:
import sqlite3 as sq
In [9]:
# 데이터베이스 파일이 저장될 경로와 파일 이름을 써서 데이터베이스에 연결 합니다.
con = sq.connect("db.sqlite")
In [10]:
#유니코드 인코딩 문제가 발생하면 해당 코드의 주석을 해제하고 실행하세요.
# con.text_factory = str
In [11]:
#메모리에서 직접 데이터베이스를 이용하는 코드입니다.
# con = sq.connect(":memory:")
In [12]:
#데이터베이스를 동작시키기 위한 Cursor 객체를 생성합니다.
#데이터베이스를 사용하기 위한 마지막 준비라고 생가가하면 됩니다.
cur = con.cursor()
In [13]:
#이제 무언가 하면 됩니다.
In [14]:
#테이블 생성
In [15]:
cur.execute("""
create table hanbit_books(
title varchar(100),
author varchar(100),
transltor varchar(100),
pub_date date,
isbn varchar(100)
)
""")
Out[15]:
In [16]:
con.commit()
In [17]:
cur.execute("""
insert into hanbit_books values(?,?,?,?,?)
""",("책 이름", "저자 이름", "번역자 이름", "2016-08-22", "97988968480011"))
Out[17]:
In [18]:
query_str = "insert into hanbit_books values (:title, :title, :title, :pub_date, :isbn)"
In [19]:
params = {
"title":"책 이름",
"pub_date": "2017-10-12",
"isbn":9788968480022
}
In [20]:
cur.execute(query_str, params)
Out[20]:
In [21]:
con.commit()
In [22]:
data = [[
"java", "홍길동", "alice", "2017-08-27", "97988945480011"
],[
"python", "alice", "bob", "2017-05-27", "97988963843434"
]]
In [23]:
#데이터를 대량으로 많이 입력 할 경우 하는 방법
cur.executemany("insert into hanbit_books values(?,?,?,?,?)", data)
Out[23]:
In [24]:
con.commit()
In [25]:
select_query = "select * from hanbit_books"
In [43]:
cur.execute(select_query)
Out[43]:
In [44]:
result = list(cur.fetchall())
for i in result:
print(i)
In [46]:
for i in result:
print(i)
In [31]:
select_q = "select * from hanbit_books where title = ?"
In [33]:
cur.execute(select_q, ("java",)) # 왜 이렇게 하는 거지 ("java", ) <-콜론
Out[33]:
In [34]:
for i in cur.fetchall():
print(i)
In [35]:
select_q2 = "select * from hanbit_books where title = :title"
In [36]:
params = {
"title" : "java"
}
In [37]:
cur.execute(select_q2, params)
Out[37]:
In [38]:
for i in cur.fetchall():
print(i)
In [47]:
query_str = "update hanbit_books set title=:chg_title where title=:title"
In [48]:
params = {
"chg_title" : "java8",
"title" : "java"
}
In [49]:
cur.execute(query_str, params)
Out[49]:
In [50]:
cur.execute("select * from hanbit_books where title like 'java%'")
Out[50]:
In [51]:
for i in cur.fetchall():
print(i)
In [52]:
cur.execute("delete from hanbit_books where title=?", ("java8",))
Out[52]:
In [53]:
cur.execute("select * from hanbit_books")
Out[53]:
In [54]:
cur.fetchall()
Out[54]:
In [ ]: