Python – Sqlite3

Sqlite3 Site

https://www.sqlite.org/

Sqlite3 Client

sqlite browser

Python 에서 Sqlite 사용

  • SQLite는 오픈 소스 데이터베이스
  • 모든 안드로이드 장치에 내장되어 있음
  • DB 서버 필요 없는 파일 기반 Embedded SQL DB 엔진
  • 파이썬에서 사용시 표준 sqlite3 모듈을 사용

Step 0: Create Table

  • sqlite client로 DB 접속

CREATE TABLE `miniboard` ( 
`idx` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
`writer` TEXT NOT NULL, 
`title` TEXT NOT NULL, 
`content` TEXT NOT NULL, 
`regdate` TEXT NOT NULL DEFAULT (datetime('now','localtime'))
)

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 1: Connect


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

Step 2: 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 3: Insert a row


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

with connection:
    cursor = connection.cursor()
    sql = "INSERT INTO `miniboard` (`writer`, `title`, `content`) VALUES (?, ?, ?)"
    cursor.execute(sql, ('mooni', 'mooni title', 'mooni content'))

    connection.commit()

with connection:
    cursor = connection.cursor()
    sql = "SELECT * FROM `miniboard` WHERE `writer`= ?"
    cursor.execute(sql, ('mooni',))
    rows = cursor.fetchone()
    print(rows)

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다