160816: 104회차

종료하기 전 티스토리 네이버 로그아웃 할 것


1. 툴

동일

추가시: 


2. 폴더

동일

추가시:


3. 사용할 사이트

동일

추가시:


4. 공부하는 것


[14] SQLite3를 이용한 데이터베이스

[01]SQLite3를 이용한 데이터베이스
 
1. SQLite3의 파이썬 API

- 파이썬 자료형에 대응하는  SQLite3자료형
 
 
- 파이썬에는 SQLite3이 기본 탑재되어 있으므로 import문의 모듈추가로
  SQLite3 API를 사용할 준비가된다.
 
- import sqlite3
 
- SQLite3 API사용순서
 
1)커넥션(Conntion) 열기 
  - sqllite3.connect('d:javadb/python/sqlite/test.db')사용
  - test.db는 해당경로에 파일이 존재하면 열고 없으면 새로 생성
 
  import sqlite3
 
  conn = sqlite3.connect('d:javadb/python/sqlite/test.db')
 
  conn.close()
 
 
2)커서(Cursor)열기
  - cursor()메소드를 사용하여 생성.
  - sql문을 실행하는 임무를 담당함.
  - sql문을 실행하기위해 excute()메소드를 이용함.
  - 레코드추가/조회/수정/삭제 수행
 
  import sqlite3
 
  conn = sqlite3.connect('d:javadb/python/sqlite/test.db')
  cursor = conn.cursor()
 
  cursor.close()
  conn.close()
 
3)커서를 이용하여 테이블 생성 및 레코드 추가/조회/수정/삭제
 
- 테이블 생성
 
>>>> table.py
import sqlite3
 
conn = sqlite3.connect('d:/javadb/python/sqlite/test.db')
cursor = conn.cursor()
 
cursor.execute("""
CREATE TABLE PHONEBOOK 
(NAME CHAR(32), PHONE CHAR(32), EMAIL CHAR(64) PRIMARY KEY)
""")
 
cursor.close()
conn.close()
 
 
- 레코드 등록
- 레코드 추가/수정/삭제시 Connection의 commit()함수 호출
 
# -*- coding:utf-8 -*-
import sqlite3
 
conn = sqlite3.connect('d:javadb/python/sqlite/test.db')
conn.text_factory = str #한글 DB에 입력시 작성
cursor = conn.cursor()
 
cursor.execute("""
INSERT INTO PHONEBOOK (NAME, PHONE, EMAIL) 
VALUES(?, ?, ?)
""", ("김길동", '021-322-1542', 'kim@python.com'))
 
id = cursor.lastrowid
print(id)
 
cursor.execute("""
INSERT INTO PHONEBOOK (NAME, PHONE, EMAIL) 
VALUES(?, ?, ?)
""", ('박길동', '021-445-2424', 'park@python.com'))
 
id = cursor.lastrowid
print(id)
 
conn.commit()
 
cursor.close()
conn.close()
 
 
- 레코드 조회
- SELECT문의 결과를 얻어올때는 커서의 fetchone(),fetchall()
  사용 
# -*- coding:utf-8 -*-
import sqlite3
 
conn = sqlite3.connect('d:javadb/python/sqlite/test.db')
conn.text_factory = str #한글을 DB에서 조회시 사용
cursor = conn.cursor()
 
cursor.execute("SELECT NAME, PHONE, EMAIL FROM PHONEBOOK")
 
 
rows = cursor.fetchall()
for row in rows:
    print ("NAME: {0}, PHONE: {1}, EMAIL: {2} ".
        format(row[0], row[1], row[2]))
 
cursor.close()
conn.close()
 
 
 
- 레코드 수정
- 레코드 추가/수정/삭제시 Connection의 commit()함수 호출
 
# -*- coding:utf-8 -*-
import sqlite3
 
conn = sqlite3.connect('d:javadb/python/sqlite/test.db')
conn.text_factory = str #한글를 DB 입력시 작성
 
cursor = conn.cursor()
 
cursor.execute("""
UPDATE PHONEBOOK SET PHONE=?, EMAIL=? WHERE NAME=?
""", ('030-1234-0000', 'kim@dong.com', '김길동'))
 
conn.commit()
 
cursor.execute("""
SELECT NAME, PHONE, EMAIL FROM PHONEBOOK
WHERE NAME=?
""", ('김길동',))
 
rows = cursor.fetchall()
for row in rows:
    print ("NAME: {0}, PHONE: {1}, EMAIL: {2} ".
        format(row[0], row[1], row[2]))
 
cursor.close()
conn.close()
 
 
- 레코드 삭제
- 레코드 추가/수정/삭제시 Connection의 commit()함수 호출
 
import sqlite3
conn = sqlite3.connect(d:javadb/python/sqlite/test.db')
conn.text_factory = str #한글을 DB에서 조회시 사용
cursor = conn.cursor()
 
cursor.execute("""
DELETE FROM PHONEBOOK WHERE EMAIL=?
""", ('kim@dong.com',))
conn.commit()
 
cursor.execute("SELECT NAME, PHONE, EMAIL FROM PHONEBOOK")
 
rows = cursor.fetchall()
for row in rows:
    print ("NAME: {0}, PHONE: {1}, EMAIL: {2} ".
        format(row[0], row[1], row[2]))
 
cursor.close()
conn.close()
 
4)커서 닫기
5)커넥션 닫기



2. Eclipse에서 SQLite3 연결

 
1) sqlitejdbc-v53.jar 다운로드
   - 강사배포
 
2) Database Development -> New Connection Profile -> SQLite 선택
 
  
 
3) New Driver Definition -> sqlitejdbc-v53.jar 선택
 
   Database :TEST
   Database Location : d:javadb\python\sqlite3\test.db 선택및 입력
 
   Test Conntect 버튼 클릭
 
 

 
4) Data Source Explorer
   edit SQL statments 선택후 
   test.sql 파일을 현재작업하는 python프로젝트의 
   sqlite3폴더생성후 저장

 
 






  



5. 수업

진도: 

hw: 


6. 할것



'Programming' 카테고리의 다른 글

160819: 106회차  (0) 2016.08.19
160817: 105회차  (0) 2016.08.17
160809: 103회차  (0) 2016.08.09
160808: 102회차  (0) 2016.08.08
160805: 101회차  (0) 2016.08.05
Posted by DAVID