220928 Python #12

김혜진·2022년 9월 28일
0

Python

목록 보기
11/24

Python #12

SQLite

조건에 따라 데이터 읽어오기

SELECT 열이름1, 열이름2, ... FROM 테이블 이름;

sqlite> select * from bookItem where author = 'lch';
id  item    author  publisher     stock
--  ------  ------  ------------  -----
1   python  lch     digitalbooks  100
3   c#      lch     hyejiwon      300
4   C++     lch     hyejiwon      400
sqlite> select * from bookItem where stock > 200;
id  item  author  publisher  stock
--  ----  ------  ---------  -----
3   c#    lch     hyejiwon   300
4   C++   lch     hyejiwon   400
sqlite> select * from bookItem where id < 3;
id  item        author  publisher     stock
--  ----------  ------  ------------  -----
1   python      lch     digitalbooks  100
2   javascript  kim     digitalbooks  200

데이터 삭제하기

DELETE FROM 테이블 이름;
DELETE FROM 테이블 이름 WHERE 조건

sqlite> delete from bookItem where stock = 300;
sqlite> select * from bookItem;
id  item        author  publisher     stock
--  ----------  ------  ------------  -----
1   python      lch     digitalbooks  100
2   javascript  kim     digitalbooks  200
4   C++         lch     hyejiwon      400

파이썬에서 SQLite에 연결하기

파이썬 코드에서 SQLite 데이터베이스 사용 순서

  • 파이썬 코드로 SQLite에 연결하고 활용하는 방법
  • 파이썬에서 SQLite 데이터베이스를 사용하는 전체 단계

데이터베이스 연결하기

  • sqlite 라이브러리를 읽어와야한다.
  • import로 파이썬에 내장되어있는 sqlite3 라이브러리를 임포트한다.
  • connect() 함수를 사용하여 'bookStoreDB' 데이터베이스에 연결한다.
  • 데이터베이스가 엇으면 새로 생성한다.
  • 리턴된 변수 conn은 데이터베이스의 연결 객체이다.
##############
# 2022.09.28 #
##############

import sqlite3
conn = sqlite3.connect('bookStore')
print('1. DB 연결 성공')

cur = conn.cursor()
print('2. 커서 생성 성공')

cur.execute('create table if not exists bookItem (id int, item char(100), author char(50), publisher char(50), stock int)')
print('3. 테이블 생성')

cur.execute("insert into bookItem values(1, 'java', 'lch', 'ebook', 200)")
cur.execute("insert into bookItem values(2, 'C++', 'kim', 'digital', 300)")
cur.execute("insert into bookItem values(3, 'C#', 'park', 'hanbit', 400)")
cur.execute("insert into bookItem values(4, 'python', 'cho', 'ebook', 500)")
print('4. 데이터 입력')

conn.commit()
print('5. 데이터 저장')

cur.execute("select * from bookItem")
print('6. 데이터 조회')

while True :
    row = cur.fetchone()
    if(row == None) :
        break
    print(row)
print('7. 데이터 출력')

conn.close()
print('8. DB 연결 종료')

출력결과
1. DB 연결 성공
2. 커서 생성 성공
3. 테이블 생성
4. 데이터 입력
5. 데이터 저장
6. 데이터 조회
(1, 'java', 'lch', 'ebook', 200)
(2, 'C++', 'kim', 'digital', 300)
(3, 'C#', 'park', 'hanbit', 400)
(4, 'python', 'cho', 'ebook', 500)
7. 데이터 출력
8. DB 연결 종료

profile
알고 쓰자!

0개의 댓글