본문 바로가기
공부/자격증

Python으로 SQLite3 연결하기 Tutorial (가계부 DB 생성하기)

by 혼밥맨 2023. 1. 18.
반응형

Python으로 SQLite3 연결하기 Tutorial (가계부 DB 생성하기)

파이썬으로 SQLite3 연결하기 Tutorial (가계부 DB 생성하기)

 

Library To Install (설치할 라이브러리)

1
pip install sqlite3
cs

https://docs.python.org/3/library/sqlite3.html

 

SQLite3이란....

SQLite의 배포판에는 sqlite3이라는 독립 실행형 명령줄 셸 프로그램이 제공됩니다. 데이터베이스 생성, 테이블 정의, 행 삽입 및 변경, 쿼리 실행 및 SQLite 데이터베이스 파일 관리에 사용할 수 있습니다. 또한 SQLite 라이브러리를 사용하는 애플리케이션을 작성하기 위한 예제 역할을 합니다.

DB 생성하기 (create_db.py)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# create_db.py
 
import sqlite3
 
conn = sqlite3.connect("expenses.db")
cur = conn.cursor()
 
cur.execute("""CREATE TABLE IF NOT EXISTS expenses
(id INTEGER PRIMARY KEY,
Date DATE,
description TEXT,
category TEXT,
price REAL)""")
 
conn.commit()
cs
expenses.db

 

가계부 프로그램 생성하기 (main.py)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# main.py
 
import sqlite3
import datetime
 
 
conn = sqlite3.connect("expenses.db")
cur = conn.cursor()
 
while True:
    print("Select an option:")
    print("1. Enter a new expense")
    print("2. View expenses summary")
 
    choice = int(input())
 
    if choice == 1:
        date = input("Enter the date of the expense (YYYY-MM-DD): ")
        description = input("Enter the description of the expense: ")
 
        cur.execute("SELECT DISTINCT category FROM expenses")
 
        categories = cur.fetchall()
 
        print("Select a category by number:")
        for idx, category in enumerate(categories):
            print(f"{idx + 1}. {category[0]}"
        print(f"{len(categories) + 1}. Create a new category")
 
        category_choice = int(input())
        if category_choice == len(categories) + 1:
            category = input("Enter the new category name: ")
        else:
            category = categories[category_choice - 1][0]
 
        price = input("Enter the price of the expense: ")
        
        cur.execute("INSERT INTO expenses (Date, description, category, price) VALUES (?, ?, ?, ?)", (date, description, category, price))        
 
        conn.commit()
 
    elif choice == 2:
        print("Select an option:")
        print("1. View all expenses")
        print("2. View monthly expenses by category")
 
        view_choice = int(input())
        if view_choice == 1:
            cur.execute("SELECT * FROM expenses")
            expenses = cur.fetchall()
            for expense in expenses:
                print(expense)
        elif view_choice == 2:
            month = input("Enter the month (MM): ")
            year = input("Enter the year (YYYY): ")
            cur.execute("""SELECT category, SUM(price) FROM expenses
                        WHERE strftime('%m', Date) = ? AND strftime('%Y', Date) = ?
                        GROUP BY category""", (month, year))
            
            expenses = cur.fetchall()
            for expense in expenses:
                print(f"Category: {expense[0]}, Total: {expense[1]}")
    
        else:
            exit()
 
    else:
        exit()
 
    repeat = input("Would you like to do something else (y/n)?\n")
    if repeat.lower() != "y":
        break
    
conn.close()
 
 
cs

반응형

댓글