728x90
DB와 연결할 DAO파일 작성
dao_emp.py파일 코드
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)
HELLO_AJAX프로젝트 안에
HELLO_AJAX패키지 안에
templates파일 생성하고
그안에 html파일 생성한다.
emp.html코드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function fn_ajax(){
console.log("fn_ajax")
var data = {'e_id':1};
$.ajax({
type:'POST',
url:'http://127.0.0.1:8000/ajax',
data : JSON.stringify(data),
success:function(json){
console.log("data pass success",json);
}
});
}
// function fn_ajax_list(){
// console.log("fn_ajax")
// var data = {'e_id':1};
// $.ajax({
// type:'POST',
// url:'ajax_list',
// data : JSON.stringify(data),
// success:function(json){
// console.log("data pass success",json);
// console.log(json.list)
// html = "";
// $.each(json.list, function(key, value){
// html += "<tr>"
// html += "<td>"+value.e_id+"</td>"
// html += "<td>"+value.e_name+"</td>"
// html += "<td>"+value.gen+"</td>"
// html += "<td>"+value.addr+"</td>"
// html += "</tr>"
// })
// $("#my_tbody").html(html);
// }
// });
// }
function fn_ajax_list(){
console.log("fn_ajax")
$.ajax({
type:'POST',
url:'ajax_list',
success:function(json){
console.log("data pass success",json);
console.log(json.result)
var list = json.list;
html = ``;
for(var i=0; i<list.length; i++){
var vo = list[i];
var e_id = vo.e_id;
var e_name = vo.e_name;
var gen = vo.gen;
var addr = vo.addr;
html += `
<tr>
<td><a href="javascript:fn_ajax_one('${e_id}')">${e_id}</a></td>
<td>${e_name}</td>
<td>${gen}</td>
<td>${addr}</td>
</tr>
`;
}
$("#my_tbody").html(html);
}
});
}
function fn_ajax_one(e_id){
console.log(e_id)
var data = {'e_id':e_id}
$.ajax({
type:'POST',
url:'emp_one',
data : JSON.stringify(data),
success:function(json){
console.log("data pass success",json);
var vo = json.vo;
// $("#e_id").attr('value',vo.e_id);
// $("#e_name").attr('value',vo.e_name);
// $("#gen").attr('value',vo.gen);
// $("#addr").attr('value',vo.addr);
$("#e_id").val(vo.e_id);
$("#e_name").val(vo.e_name);
$("#gen").val(vo.gen);
$("#addr").val(vo.addr);
}
});
}
function emp_insert(){
var e_id = $('#e_id').val();
var e_name = $('#e_name').val();
var gen = $('#gen').val();
var addr = $('#addr').val();
console.log("insert"+e_id,e_name,gen,addr);
var data = {
"e_id":e_id,
"e_name":e_name,
"gen":gen,
"addr":addr
}
$.ajax({
type:'POST',
url:'emp_insert',
data : JSON.stringify(data),
success:function(json){
console.log("data pass success",json);
fn_ajax_list()
alert("정상적으로 정보가 추가 되었습니다.")
}
});
}
function emp_update(){
var e_id = $('#e_id').val();
var e_name = $('#e_name').val();
var gen = $('#gen').val();
var addr = $('#addr').val();
console.log("update"+e_id,e_name,gen,addr);
var data = {
"e_id":e_id,
"e_name":e_name,
"gen":gen,
"addr":addr
}
$.ajax({
type:'POST',
url:'emp_update',
data : JSON.stringify(data),
success:function(json){
console.log("data pass success",json);
fn_ajax_list()
alert("정상적으로 정보가 수정 되었습니다.")
}
});
}
function emp_delete(){
var e_id = $('#e_id').val();
console.log("update"+e_id,e_name,gen,addr);
var data = {
"e_id":e_id,
}
$.ajax({
type:'POST',
url:'emp_delete',
data : JSON.stringify(data),
success:function(json){
console.log("data pass success",json);
fn_ajax_list()
alert("정상적으로 정보가 삭제 되었습니다.")
}
});
}
</script>
</head>
<body>
EMP<br/>
<a href="javascript:fn_ajax()">ajax</a><br/>
<a href="javascript:fn_ajax_list()">ajax_list</a>
<table border="1px">
<thead>
<tr>
<td>이름</td>
<td>사번</td>
<td>성별</td>
<td>주소</td>
</tr>
</thead>
<tbody id="my_tbody">
<tr>
<td colspan="4">데이터가 없습니다</td>
</tr>
</tbody>
</table>
<table border="1px">
<tr>
<td>사번</td>
<td>
<input type="text" id="e_id">
</td>
</tr>
<tr>
<td>이름</td>
<td>
<input type="text" id="e_name">
</td>
</tr>
<tr>
<td>성별</td>
<td>
<input type="text" id="gen">
</td>
</tr>
<tr>
<td>주소</td>
<td>
<input type="text" id="addr">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="추가" onclick="emp_insert()">
<input type="button" value="수정" onclick="emp_update()">
<input type="button" value="삭제" onclick="emp_delete()">
</td>
</tr>
</table>
</body>
</html>
views.py파일 코드
from django.shortcuts import render
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from HELLO_AJAX.dao_emp import DaoEmp
def emp(request):
return render(request, 'emp.html')
@csrf_exempt
def ajax(request):
data = json.loads(request.body)
# do something
print(data['e_id'])
context = {
'result': data,
}
return JsonResponse(context)
@csrf_exempt
def ajax_list(request):
de = DaoEmp()
list = de.selectList()
return JsonResponse({'list':list})
@csrf_exempt
def emp_one(request):
e_id = json.loads(request.body)
print(e_id)
de = DaoEmp()
vo = de.selectOne(e_id['e_id'])
return JsonResponse({'vo':vo})
@csrf_exempt
def emp_insert(request):
data = json.loads(request.body)
print("data",data)
e_id = data['e_id']
e_name = data['e_name']
gen = data['gen']
addr = data['addr']
print(e_id,e_name,gen,addr)
de = DaoEmp()
cnt = de.insert(e_id, e_name, gen, addr)
return JsonResponse({'cnt':cnt})
@csrf_exempt
def emp_update(request):
data = json.loads(request.body)
print("data",data)
e_id = data['e_id']
e_name = data['e_name']
gen = data['gen']
addr = data['addr']
print(e_id,e_name,gen,addr)
de = DaoEmp()
cnt = de.update(e_id, e_name, gen, addr)
return JsonResponse({'cnt':cnt})
@csrf_exempt
def emp_delete(request):
data = json.loads(request.body)
print("data",data)
e_id = data['e_id']
print(e_id)
de = DaoEmp()
cnt = de.delte(e_id)
return JsonResponse({'cnt':cnt})
urlpatterns를 설정해준다
path('url주소',메서드 들어있는 파일.호출할 메소드),
여기서
'Python > 장고DJANGO' 카테고리의 다른 글
파이썬(DJANGO) HTML DB연동 select하기(MVC패턴) (0) | 2023.07.06 |
---|---|
파이썬(DJANGO) HELLO_EMP 연습하기(SQL연동) (0) | 2023.07.05 |
파이썬(DJANGO) HELLO_DJANGO 연습하기(HTML연동) (0) | 2023.07.05 |
파이썬(DJANGO) dao 만들기 (0) | 2023.07.05 |
파이썬(DJANGO) 패키지 만들기 (0) | 2023.07.05 |