일단 만들기
파이썬 DB연결 게시판 기능 (웹X, 콘솔구현)
똥바보
2022. 2. 16. 17:39
저번 포스팅에 이어서 오늘은 게시판 만들기입니다.
웹이 아니라 콘솔에서 작동하는 프로그램이고
언어는 파이썬을 이용해 코딩합니다.
MySQL DB와 연결, IDE는 파이참을 사용했습니다.
아래의 포스팅이 참고에 도움이 될 것 같습니다.
<게시판>에 들어 갈 기능은 아래와 같습니다.
글쓰기 (로그인상태에서만 가능. 작성자=로그인id)
글 검색1 - (글 번호로)
글 검색2 - (작성자로)
글 검색3 - (타이틀로)
글 수정 기능
글 삭제 기능
전체목록보기 기능
디렉토리는 좌측과 같이 만들었습니다.
참고 : __init__.py 파일을 만들어주면 자동으로 디렉토리->파이썬 패키지가 됩니다. ㅎㅎ
DB 스케마
create table board(
num int primary key auto_increment,
writer varchar(20) not null,
w_date date,
title varchar(30),
content varchar(100),
constraint fk_b_writer
foreign key(writer) references member(id)
on delete cascade
);
__init__.py
__all__=[
'vo',
'menu',
'service',
'dao_db'
]
__init__.py에는 패키지를 구성하는 파일명을 다 적어주면 됩니다.
vo.py
class board:
def __init__(self, num:int=0, writer:str=None, w_date:str=None,
title:str=None, content:str=None):
self.num=num
self.writer=writer
self.w_date=w_date
self.title=title
self.content=content
def __str__(self):
return 'num'+str(self.num)+'/writer: '+self.writer+'/w_date: '\
+str(self.w_date)+'/title: '+self.title+'/content: '+self.content
vo를 작성해줍니다.
self. 는 자바에서 this.와 비슷하죠~
dao_db.py
import pymysql
from board.vo import Board
# Dao
class BoardDao:
def __init__(self):
self.conn = None
def connect(self):
self.conn = pymysql.connect(host='localhost', user='유저아이디', password='유저비밀번호', db='연결할 디비 이름', charset='utf8')
def disconn(self):
self.conn.close()
# 추가 메서드
def insert(self, a: Board):
# 1. db 커넥션 수립
self.connect()
# 2. 사용할 cursor객체 생성. db 작업 메서드가 이 클래스에 정의되어 있으므로 꼭 필요.
cursor = self.conn.cursor()
# 3. 실행할 sql문 정의
sql = 'insert into Board(writer, w_date, title,content) values(%s, now(), %s, %s)'
# 4. sql 문에 %s를 사용했다면 각 자리에 들어갈 값을 튜플로 정의
d = (a.writer, a.title, a.content)
# 5. sql 실행(실행할 sql, %s매칭한 튜플)
cursor.execute(sql, d)
# 6. 쓰기동작(insert, update, delete) 에서 쓰기 완료
self.conn.commit()
# db 커넥션 끊음
self.disconn()
# 검색 메서드
def select(self, num: int):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성
sql = 'select*from Board where num=%s'
d = (num,)
cursor.execute(sql, d) # sql 실행
row = cursor.fetchone() # fetchone() : 현재 커서 위치의 한 줄 추출
if row:
return Board(row[0], row[1], row[2], row[3], row[4])
except Exception as e:
print(e)
finally:
self.disconn()
# 작성자로 가져오기
def selectByWriter(self, writer: str):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성
sql = 'select*from board where writer like %s'
d = (writer,)
cursor.execute(sql, d) # sql 실행
res = [Board(row[0], row[1], row[2], row[3], row[4]) for row in cursor]
# for row in cursor:
# res.append(Board(row[0], row[1], row[2], row[3], row[4]))
return res
except Exception as e:
print(e)
finally:
self.disconn()
# 글 제목으로 가져오기
def selectByTitle(self, title: str):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성
sql = 'select*from board where title like %s'
d = (title,)
cursor.execute(sql, d) # sql 실행
res = [Board(row[0], row[1], row[2], row[3], row[4]) for row in cursor]
# for row in cursor:
# res.append(Board(row[0], row[1], row[2], row[3]))
return res
except Exception as e:
print(e)
finally:
self.disconn()
# 삭제(name)
def delete(self, num: int):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성
sql = 'delete from board where num = %s'
d = (num,)
cursor.execute(sql, d) # sql 실행
self.conn.commit()
return print('삭제가 완료되었습니다.')
except Exception as e:
print(e)
finally:
self.disconn()
def update(self, a: Board):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성
sql = 'update board set title=%s, content=%s where num = %s'
d = (a.title, a.content, a.num,)
cursor.execute(sql, d) # sql 실행
self.conn.commit()
return print('수정이 완료 되었습니다.')
except Exception as e:
print(e)
finally:
self.disconn()
def selectAll(self):
try:
self.connect() # db연결
cursor = self.conn.cursor() # 사용할 커서 객체 생성글
sql = 'select*from board'
cursor.execute(sql)
res = [Board(row[0], row[1], row[2], row[3], row[4]) for row in cursor]
return res
except Exception as e:
print(e)
finally:
self.disconn()
menu.py
from board.service import BoardService
class Menu:
def __init__(self):
self.service = BoardService()
def run(self):
while True:
m = input('1.글쓰기 2.글 번호로 검색 3.글 작성자로 검색 4.글 타이틀로 검색 5.글 수정 6.글 삭제 7.전체 출력 8.종료 \n')
if m == '1':
self.service.addBoard()
elif m == '2':
self.service.getByNum()
elif m == '3':
self.service.getByWriter()
elif m == '4':
self.service.getByTitle()
elif m == '5':
self.service.editBoard()
elif m == '6':
self.service.delBoard()
elif m == '7':
self.service.printAll()
elif m == '8':
break
if __name__ == '__main__':
m = Menu()
m.run()
메뉴까지 만들면 끝!