본문 바로가기
Python/장고DJANGO

파이썬(DJANGO) HTML DB연동 select하기(MVC패턴)

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

DAO클래스

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)

 

 


 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

{{data}}
<h1>EMP_LIST</h1>
<table border="1">
	<tr>
		<td>사번</td>
		<td>이름</td>
		<td>성별</td>
		<td>주소</td>
	</tr>
{% for i in data %}
	<tr>
		<td><a href="emp_detail?e_id={{i.e_id}}">{{i.e_id}}</a></td>
		<td>{{i.e_name}}</td>
		<td>{{i.gen}}</td>
		<td>{{i.addr}}</td>
	</tr>
{% endfor %}

</table>


</body>
</html>

여기서 사번을 누르게 되면 

<a href="emp_detail?e_id={{i.e_id}}">{{i.e_id}}</a>

href="emp_detail" = views.py안에 있는 emp_detail 메소드로 보낸다.

 


그렇게 되면 emp_detail에서 request객체로 값을 받아서

render로 다시 값을 보낸다.

 

 

그럼 여기서 다시 값을 {{ }} 키값으로 받아서 출력한다.