본문 바로가기
인터페이스 개발/Python

Python - 파일[데이터베이스] - SQlite 데이터 베이스

by cooluk 2020. 7. 29.

Chap.14 파일[데이터베이스] - SQlite 데이터 베이스

 

데이터베이스

SQlite 데이터 베이스

 

SQlite 데이터 베이스

 

 

SQLite Download Page

Templates (1) and (2) are used for source-code products. Template (1) is used for generic source-code products and templates (2) is used for source-code products that are generally only useful on unix-like platforms. Template (3) is used for precompiled bi

www.sqlite.org

 

내 PC > 속성 > 고급 시스템 설정 > 환경 변수 > 시스템 변수 > Path > 편집 > C:\sqlite 추가

>> cd \temp
>> sqlite3

인메모리 데이터 베이스 - 끄면 사라짐 (연습용)
명령은 . 으로 시작한다.
.exit 끝

 

>> sqlite3 test.db (실행)

CREATE TABLE tblAddr(
	NAME CHAR(16) PRIMARY KEY,
	phone CHAR(16),
	addr TEXT
);

insert into tblAddr values('홍길동', '010-111', '서울');

select * from tblAddr;

결과

 

.header on
.mode column

select * from tblAddr;

결과

 

  • Python 연동

# DB+App.py

import sys
from myapp import Application, MenuItem
import MySQLdb
from addr_repository import AddressRepositrory
from addr_ui import *

import sqlite3  # sqlite3

class DBApp(Application):
    def __init__(self):
        super().__init__()
        # self.db = MySQLdb.connect(db="sqldb", host="localhost",
        #                           user="root", passwd="1234", charset='utf8')  # sqlite3

        self.db = sqlite3.connect("c:/temp/test.db")  # sqlite3
        self.repo = AddressRepositrory(self.db)

    def create_menu(self, menu):
        menu.add(MenuItem("목록", self.print_list))
        menu.add(MenuItem("검색", self.search))
        menu.add(MenuItem("추가", self.add))
        menu.add(MenuItem("수정", self.update))
        menu.add(MenuItem("삭제", self.remove))
        menu.add(MenuItem("종료", self.exit))

    def exit(self):
        answer = input("종료하시겠습니까?([y]/n) ")
        if answer in ["y", "Y", ""]:
            self.repo.close()
            self.db.close()
            sys.exit(0)

    def print_list(self):
        total = self.repo.get_total()
        rows = self.repo.get_list()
        print_list(total, rows)


    def add(self):
        data = input_addr_info()
        self.repo.insert(data)
        self.db.commit()
        print("추가 완료")

    def remove(self):
        name  = input("이름: ")
        self.repo.remove(name)
        self.db.commit()
        print("삭제 완료")


    def update(self):
        name  = input("이름: ")
        data = self.repo.get_one(name)
        if not data:
            print(f"{name} 데이터가 없습니다.")
            return

        data = input_now_addr(data)
        self.repo.update(data)
        self.db.commit()
        print("수정 완료")



    def search(self):
        name = input("이름   : ")
        where = f"WHERE name LIKE '%{name}%'"
        total = self.repo.get_total(where)
        rows = self.repo.get_list(where)
        print_list(total, rows)


if __name__ == '__main__':
    app = DBApp()
    app.run()

결과

[메뉴] 0:목록  1:검색  2:추가  3:수정  4:삭제  5:종료  
선택] 0
==================================================
No   이름        전화번호      주소         
--------------------------------------------------
1 : 홍길동        010-111    서울         
==================================================
(총 1 건)
[메뉴] 0:목록  1:검색  2:추가  3:수정  4:삭제  5:종료  
선택] 

 

 

  • 사용자 관리

사용자 생성

create user 'iot_user'@'%' identified by '1234';

 

권한 부여

grant all privileges on sqlDB.* to 'iot_user'@'%';

 

파일 > 세션 관리자 > 신규 > 저장 > 열기

댓글