Python

Python - Sqlite3 활용

2020. 5. 29. 12:09

Python - Sqlite3

Sqlite3 Site

https://www.sqlite.org/

Sqlite3 Client

sqlite browser

 

DB Browser for SQLite

DB Browser for SQLite The Official home of the DB Browser for SQLite Screenshot What it is DB Browser for SQLite (DB4S) is a high quality, visual, open source tool to create, design, and edit database files compatible with SQLite. DB4S is for users and dev

sqlitebrowser.org

Download 클릭
자신에게 맞는 버전 선택

Python 에서 Sqlite 사용

  • SQLite는 오픈 소스 데이터베이스

  • 모든 안드로이드 장치에 내장되어 있음

  • DB 서버 필요 없는 파일 기반 Embedded SQL DB 엔진

  • 파이썬에서 사용시 표준 sqlite3 모듈을 사용

Python에서 SQLite사용하는 일반적인 절차

  • sqlite3 모듈을 import

  • sqlite3.connect() 메소드를 사용하여 SQLite 에 Connect

  • 접속할 DB 파일명을 파라미터로 지정

  • DB 접속이 성공하면, Connection 객체로부터 cursor() 메서드를 호출

  • Cursor 객체의 메서드를 통해 SQLite 서버와 작업 관리

  • Cursor 객체의 execute() 메서드를 사용하여 SQL 문장을 DB 서버로 전송

  • SQL 쿼리의 경우 Cursor 객체의 fetchall(), fetchone(), fetchmany() 등의 메서드를 사용

  • 데이타를 서버로부터 가져온 후, Fetch 된 데이타를 사용

  • Insert, Update, Delete 등의 DML(Data Manipulation Language) 문장을 실행

  • Connection 객체 commit() 은 실제로 DML 문장을 서버에 실제 실행

  • Connection 객체 rollback() 실행 으로 DML 문장 취소

  • Connection 객체의 close() 메서드를 사용하여 DB 연결 닫기

Step 0. Create DB

python으로 db만들기

Step 1. Sqlite로 DB연결 및 test데이터 작성

Step 0 에서 만든 db 선택
'F5'를 누르면 실행됨

Step 2. Connect

import sqlite3
connection = sqlite3.connect('python.db')

Step 3. Execute query

# fetchone
import sqlite3
connection = sqlite3.connect('python.db')

with connection:
	cursor = connection.cursor()
    sql = "select * from miniboard order by idx desc "
    #sql = "select * from miniboard where idx = ? order by idx desc",(3,)"

    cursor.execute(sql)
    #cursor.execute(sql, ('1',))

    rows = cursor.fetchone()
    print(rows)
    
# fetchall
import sqlite3

connection = sqlite3.connect('python.db')

with connection:
    cursor = connection.cursor()
    sql = "select * from `miniboard` order by idx desc "
    cursor.execute(sql)
    rows = cursor.fetchall()
    for row in rows:
        print(row)

Step 4. Insert & Read

출처 : http://thecoding.kr/category/phython/python-sqlite/