728x90
반응형

DB 프로그램 실습

🍀 DB프로그램

  • X : 입력 값 바뀜
  • △ : 고정으로 둘 수도 있고, 안 둘 수도 있다
  • 나머지 : 무조건 고정 → class로 설정

    1. 데이터베이스 설정 정보 준비
    2. DB 접속하기 : 커넥션(connect)
    3. 커서 받아오기 : cursor()
    4. 구문 작성하기 : sql(조회, 입력, 수정, 삭제)  --- X
    5. 구문 실행하기 :  execute() -> 결괏값은 체크 --- △
    6. 조회인 경우 커서에서 데이터 추출하기 --- △
            → 한건 : fetchone()
            → 여러 건 : fetchall()
    7. 조회결과 데이터프레임 또는 웹페이지에 출력 --- △
        →  데이터프레임 : pd.DataFrame(여러 건), pd.DataFrame([한건])
    8. 조회가 아닌 경우 : 처리 결과 조건으로 확인하기 if "처리 성공" else "처리 실패" --- △
    9. DB정보 반환하기
            - 반환 순서 : cursor > connect

🍀 class 설정

  1. 클래스 생성
    - 클래스 이름 : PowerClass
  2. 클래스 내에 함수들 정의
  3. 외부에서 조회/입력/수정/삭제 처리하기

🍀 작성한 코드

class PowerClass:
    def __init__(self):
        self.conn = None
        self.host = "localhost"
        self.user = "gjuser"
        self.password = "dbdb"
        self.db = "gjdb"
        self.charset = "utf8"
        self.cursorclass = pymysql.cursors.DictCursor
        self.autocommit = True
        
    def connect(self):
        try:
            self.conn = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                db=self.db,
                charset=self.charset,
                autocommit=self.autocommit,
                cursorclass=self.cursorclass
            )
            print("DB접속 성공 >>> ", self.conn)
        except Exception as e:
            print("DB Server Checking...", e)

    
    def cursor(self):
        cur = self.conn.cursor()
        return cur

    def close(self):
        self.cur = self.conn.cursor()
        try:
            self.cur.close()
            self.conn.close()
            print("접속종료")
        except :
            print("이미 모든 커서와 접속 정보가 반납되었습니다.")
def read(sql, cur):
    if sql[:6] == "Select" :
        cur.execute(sql)
        rows = cur.fetchall()
        ymd_power_df = pd.DataFrame(rows)
        print(ymd_power_df)
    else:
        print('다시입력')

def insert(sql, cur):
    if sql[:6] == "Insert" :
        rs_cnt = cur.execute(sql)
        if rs_cnt > 0:
            print(f'{rs_cnt}건이 입력되었습니다.')
        else:
            print(f'입력되지 않았습니다')
    else:
        print('다시입력')

def update(sql, cur):
    if sql[:6] == "Update" :
        rs_cnt = cur.execute(sql)
        if rs_cnt > 0:
            print(f'{rs_cnt}건이 수정되었습니다.')
        else:
            print(f'수정되지 않았습니다')
    else:
        print('다시입력')
            

def delete(sql, cur):
    if sql[:6] == "Update" :
        rs_cnt = cur.execute(sql)
        if rs_cnt > 0:
            print(f'{rs_cnt}건이 삭제되었습니다.')
        else:
            print(f'삭제되지 않았습니다')
    else :
        print('다시입력')
def main():
    db = PowerClass()
    db.connect()
    cur = db.cursor()
     
    
    while True:
        choice = input("""
                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                        """)
        

        if choice == "1":
            sql = input("""
                        sql 작성하기
                    """)
            read(sql, cur)
               
        elif choice == "2":
            sql = input("""
                        sql 작성하기
                    """)
            insert(sql, cur)
                                                                                              
        elif choice == "3":
            sql = input("""
                        sql 작성하기
                    """)
            update(sql, cur)
        
        elif choice == "4":
            sql = input("""
                        sql 작성하기
                    """)
            delete(sql, cur)

        elif choice == "5":
            db.close()
            break
               
        else:
            print("다시 선택해주세요")

if __name__ == "__main__":
    main()
DB접속 성공 >>>  <pymysql.connections.Connection object at 0x000001E355B99150>

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         2

                        sql 작성하기
                     Insert Into time_power_demand(         ymd, time, power     ) Values (         '2020-12-31', '24시', 1234     )
1건이 입력되었습니다.

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         1

                        sql 작성하기
                     Select * From time_power_demand         Where ymd = '2020-12-31'
          ymd time   power
0  2020-12-31  241234.0

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         3

                        sql 작성하기
                     Update time_power_demand set power = 5679         Where ymd = '2020-12-31'             And time = '24시'
1건이 수정되었습니다.

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         1

                        sql 작성하기
                     Select * From time_power_demand         Where ymd = '2020-12-31'
          ymd time   power
0  2020-12-31  245679.0

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         4

                        sql 작성하기
                     Delete         From time_power_demand         Where ymd = '2020-12-31'             And time = '24시'
1건이 삭제되었습니다.

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         1

                        sql 작성하기
                     Select * From time_power_demand         Where ymd = '2020-12-31'
Empty DataFrame
Columns: []
Index: []

                        < 조회/입력/수정/삭제 하기>
                        1. 조회
                        2. 입력
                        3. 수정
                        4. 삭제
                        5. 접속종료
                        원하는 번호(1~4)를 선택하세요
                         5
접속종료
728x90
반응형

+ Recent posts