본문 바로가기
Python/장고DJANGO

파이썬(DJANGO) dao 만들기

by 미눅스[멘토] 2023. 7. 5.
728x90

 

import pymysql
class DaoEmp:
    # print("생성자")
    def __init__(self):
        self.conn = pymysql.connect(host='127.0.0.1', user='root', password='python',
                         db='python', charset='utf8', port=3304)


        # Connection 으로부터 Dictoionary Cursor 생성
        self.curs = self.conn.cursor(pymysql.cursors.DictCursor)
        
    #메소드
    def selectList(self):
        # SQL문 실행
        sql = """
        select
            e_id,
            e_name,
            gen,
            addr
        from emp
        """
        self.curs.execute(sql)
        
        list = self.curs.fetchall()
        return list
    
    #셀렉트
    def selectOne(self,e_id):
        # SQL문 실행
        sql = f"""
        select * from emp
        where
             e_id='{e_id}'
        """
        self.curs.execute(sql)
        list = self.curs.fetchall()
        return list[0]
    
    #인설트
    def insert(self,e_id,e_name,gen,addr):
        # SQL문 실행
        sql = f"""
        insert into emp
            (e_id, e_name, gen, addr) 
        values
            ('{e_id}','{e_name}','{gen}','{addr}')
        """
        cnt = self.curs.execute(sql)
        self.conn.commit()
        return cnt
    
    #업데이트
    def update(self,e_id,e_name,gen,addr):
        # SQL문 실행
        sql = f"""
        update emp 
        set
            e_name = '{e_name}',
            gen = '{gen}',
            addr = '{addr}'
        where
            e_id = '{e_id}'
        """
        cnt = self.curs.execute(sql)
        print("cnt",cnt)
        print("curs.rowcount",self.curs.rowcount)
        self.conn.commit()
        return cnt
    
    #딜리트
    def delte(self,e_id):
        # SQL문 실행
        sql = f"""
        delete from emp
        where
            e_id = '{e_id}'
        """
        cnt = self.curs.execute(sql)
        print("cnt",cnt)
        print("curs.rowcount",self.curs.rowcount)
        self.conn.commit()
        return cnt
    
    # 메모리에서 사라질때 호출됨
    def __dal__(self):
        self.curs.close()
        self.conn.close()

if __name__ == '__main__':
    de = DaoEmp()
    cnt = de.delte('3')
    # cnt = de.selectList()
    print(cnt)