2022.08.31 ~ 2022.09.01
https://docs.google.com/document/d/1hNcI43atV4chIge6AP8-X_sF8iXuoDkZjTucJvA980M/edit?usp=sharing
코드비교분석_답안1_220901
코드 비교 분석 답안1.zip과 빅데이터분석_모의평가_4_답안지.py(이하 답안지.py)를 비교합니다. 코드의 모든 부분의 차이점을 비교한 것이 아니라, 일부만을 비교했습니다. 가로로 긴 코드는 코드
docs.google.com
<답안1 코드와 나의 코드 비교 분석>
- 선생님께서 주신 답안1 코드와 나의 코드 비교
- 수정하고 싶은 점과 타 학습자들의 조언 정리
- 첨삭 사항 반영
<타 학습자 의견 작성>
- 문서를 공유하여 나의 의견에 대해 다른 학습자들이 동의/비동의 의견을 작성해줌
2022.09.02 ~ 2022.09.05
https://docs.google.com/document/d/19mxcfg3DUMyzuCp1iN3-r6Dyy2PiLAFVRVDqQuBxn1A/edit?usp=sharing
코드비교분석_답안2_220905
코드 비교 분석2 반영하고 싶은 기능 1 1. 파일 구성 파일 분리 필터, 텍스트파일 관리 등 기능별로 분리하면 좋을 것 같다. 다만 나의 코드는 테이블을 기준으로 구분된 것이 아니기 때문에 기준
docs.google.com
<답안2 코드와 나의 코드 비교 분석>
- 선생님께서 주신 답안2 코드와 나의 코드 비교
- 비교 항목 중 나의 코드에 반영하고 싶은 항목 문서 최상단에 정리
<타 학습자 의견 작성>
- 문서를 공유하여 나의 의견에 대해 다른 학습자들이 동의/비동의 의견을 작성해줌
2022.09.07 ~ 2022.09.08
<코드 개선>
- 반영하고 싶은 항목 작성했던 것 참고하여 코드 수정
<요구사항 반영>
- 요구사항은 타 학습자의 코드에서 추출한 것
- 타 학습자 코드를 벤치마킹 하는 과정
- 1. 반복 코드 함수화
- 2. 파일 분할 (import 사용)
- 3. 함수와 클래스 세분화
- 4. 향상된 for문 (또는 이중for문) 사용
- 5. zip()함수 응용
- 6. map()함수 응용
<완성 코드>
- 테이블이 없을 경우 모의평가_4_초기화의 쿼리들을 실행한 후 main.py 실행
https://drive.google.com/file/d/1uNOp0-QRNOUcF4prMl2Fr3Cp8hdwpezB/view?usp=sharing
- main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | import os import sys import datetime # 날짜 유효성 검사 위함 ### <요구사항-2> 반영 ### # 22-09-05 : 파일 분리 from ShowGraph import * from DBController import * # 22-09-06 : FileController 파일 생성 from FileController import * from wcwidth import wcswidth # 한글이 포함된 문자열에 간격 맞추기 솔루션을 제공하는 라이브러리 def fmt(x, w, align='l'): """ 동아시아문자 폭을 고려하여, 문자열 포매팅을 해 주는 함수. w 는 해당 문자열과 스페이스문자가 차지하는 너비. align 은 문자열의 수평방향 정렬 좌/우/중간. """ x = str(x) l = wcswidth(x) s = w-l if s <= 0: return x if align == 'l': return x + ' '*s + '| ' # 공백 끝마다 구분선 '| ' 추가 if align == 'c': sl = s//2 sr = s - sl return ' '*sl + x + ' '*sr return ' '*s + x def create_table(): # 22-09-05 : 테이블 없을 시 생성되도록 메서드 추가 sql1 = """create table if not exists product( pCode varchar(4) not null Primary Key, pName varchar(20) not null, unitPrice int not null, discountRate decimal(5,2) not null default 1.0) """ sql2 = """create table if not exists sales( seqNo int not null auto_increment, sCode varchar(4) not null, sDate timestamp default current_timestamp on update current_timestamp, Qty int not null, Amt decimal(12,2) default 0, constraint sales primary key(seqNo, sCode) )""" cd1 = ConnectDB() # DB에 Connect하는 클래스 생성 cd1.db_commit(sql1) # 쿼리 반영 cd1.db_commit(sql2) del cd1 # 클래스 소멸 ### <요구사항-3> 반영 ### class ShowTables: # 리스트(테이블)을 출력하는 함수. 출력부마다 호출하여 사용 def print_product(self, rows): # 제품 테이블 print('{}{}{}{}'.format(fmt('pCode', 10), fmt('pName', 20), fmt('UnitPrice', 12), 'discountRate')) print('-'*60) for row in rows : print("{}{}{}{}".format(fmt(row[0], 10), fmt(row[1], 20), fmt(row[2], 12), row[3])) def print_sales(self, rows): # 판매 테이블 print('{}{}{}{}{}'.format(fmt('seqNo', 6), fmt('sCode', 6), fmt('sDate', 20), fmt('Qty', 6), 'Amt')) print('-'*60) for row in rows : print("{}{}{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20), fmt(row[3], 6), row[4])) def print_sales_pname(self, rows): # 판매테이블과 제품테이블의 pname print('{}{}{}{}{}{}'.format(fmt('seqNo', 6), fmt('sCode', 6), fmt('pName', 20), fmt('sDate', 20), fmt('Qty', 6), 'Amt')) print('-'*80) for row in rows : print("{}{}{}{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20), fmt(row[3], 20), fmt(row[4], 6), row[5])) # 22-09-07 : Find 클래스 삭제 후 Find 클래스 호출부분은 DBController를 활용한 코드로 대체 class Read: # 테이블 조회를 수행하는 클래스 # 22-09-07 : Find 클래스와 통합 및 ConnectDB 클래스를 활용하여 쿼리 반영하는 방식으로 변경 target = '' target_table = '' target_name = '' def __init__(self, target): self.target = target if self.target == 'p': self.target_name = '제품'; self.target_table = 'product' else : self.target_name = '판매'; self.target_table = 'sales' # 메인의 메뉴 번호와 동일 def read_all(self): cd1 = ConnectDB() # Find 클래스가 아닌 ConnectDB클래스의 객체 생성하여 쿼리 반영 tables = ['p', 's'] # 테이블 첫글자 read_sql = ["select * from "+f"{self.target_table}", # 각 테이블 조회 sql """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;"""] ### <요구사항-5> 반영 ### table_read_sql = dict(zip(tables, read_sql)) # 테이블에 해당하는 sql을 딕셔너리로 생성 # 22-09-08 : if문으로 p, s를 구분하여 쿼리문을 지정하지 않고 딕셔너리 키값(p,s)에 따라 쿼리문을 지정한다. rows = cd1.db_find_all(table_read_sql[self.target], "전체 목록 조회 오류입니다.") if rows: print('\n<<<목록 조회입니다>>>') print('===테이블 조회 1===') st1 = ShowTables() # 타겟 테이블에 따라 다른 출력메서드 호출 if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) else: print('출력할 데이터가 없습니다.') del cd1 # 클래스 소멸 def read_code(self): cd1 = ConnectDB() # 클래스 생성 st1 = ShowTables() if self.target == 'p' : sql = "select * from "+f"{self.target_table}" else : sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" rows = cd1.db_find_all(sql, "전체 목록 조회 오류입니다.") if rows: print('\n<<<전체 목록 조회>>>') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) print('\n<<<개별 조회(코드)입니다>>>') in_Code = input('조회할 코드를 입력하세요 : ') if self.target == 'p': sql = "select * from product where pCode =" + f"'{in_Code}'" rows = cd1.db_find_all(sql, "제품코드 개별 조회 오류입니다.") if rows: st1.print_product(rows) else : print("입력하신 코드에 해당하는 제품이 없습니다.") else: sql = "select * from sales where sCode =" + f"'{in_Code}'" rows = cd1.db_find_all(sql, "판매코드 개별 조회 오류입니다.") if rows: st1.print_sales(rows) else : print("입력하신 코드에 해당하는 판매가 없습니다.") del cd1 # 클래스 소멸 def read_name(self): cd1 = ConnectDB() st1 = ShowTables() if self.target == 'p' : sql = "select * from "+f"{self.target_table}" else : sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" rows = cd1.db_find_all(sql, "전체 목록 조회 오류입니다.") if rows: print('\n<<<전체 목록 조회>>>') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) print(f'\n<<<개별 조회({self.target_name}명)입니다>>>') in_pName = input('조회할 제품명을 입력하세요 : ') if self.target=='p': sql = "select * from product where pName =" + f"'{in_pName}'" rows = cd1.db_find_all(sql, "제품명 개별 조회 오류입니다.") if rows: st1.print_product(rows) else : print("입력하신 제품명에 해당하는 제품이 없습니다.") # else: sql = "select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where P.pName =" + f"'{in_pName}'" + "and S.sCode = P.pCode;" rows = cd1.db_find_all(sql, "제품명 개별 조회 오류입니다.") if rows: st1.print_sales(rows) else : print("입력하신 제품명에 해당하는 판매가 없습니다.") del cd1 class InputFilter: # 22-09-07 : 판별 결과를 True/False로 리턴했었으나 # 전역변수를 삭제하고 결과가 True일 경우 사용자 입력값을, False일 경우 None을 리턴하도록 함 def set_pname(self, pname) : if pname == '' or len(pname) < 0 : print("공백은 입력 불가능합니다.") pname = None return pname # def set_uprice(self, uprice) : if uprice == '' or len(uprice) < 0 : print("공백은 입력 불가능합니다.") uprice = None elif uprice.isdigit() == False: # 정수만 입력 가능 # 사은품같은 0원제품도 있을 수 있어 0 입력시 오류 출력 안함 print('숫자로만 입력해주세요.') uprice = None return uprice # def set_drate(self, drate) : if drate == '' : print("1.0으로 입력됩니다.") drate = '1.0' return drate try : drate = float(drate) except : print("실수만 입력 가능합니다.") drate = None return drate # 해당 컬럼은 default값이 있기 때문에 공백 입력 가능 if 0 > drate or 100 < drate: # 퍼센트이기 때문에 0~100 사이의 값만 입력 가능 print('0부터 100까지의 수만 입력 가능합니다.') drate = None return drate # def set_qty(self, qty) : if qty == '' or len(qty) < 0 : print("\n공백은 입력 불가능합니다.") qty = None elif qty.isdigit() == False: # 정수만 입력 가능 print('\n숫자로만 입력해주세요.') qty = None elif int(qty) < 0: print("\n0개부터 입력 가능합니다.") qty = None return qty def set_date(self, date) : if date == '' or len(date) < 0 : print("\n내용을 입력하지 않으시면 현재 날짜로 등록됩니다.") date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') print(date, type(date)) # elif bool(re.match(r'\d{4}-\d{2}-\d{2}', date)): # %Y-%m-%d 형태로 입력되었을 때 try: datetime.datetime.strptime(date, "%Y-%m-%d") print("날짜만 입력하셔서 시간은 00:00:00으로 등록됩니다.") date = date + " 00:00:00" except: print("\n년, 월, 일이 적합한지 다시 한번 확인해주세요.") date = None # elif bool(re.match(r'\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}', date)): # %Y-%m-%d %H:%M:%S 형태로 입력되었을 때 try: datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') except: print("\n년, 월, 일과 시간이 적합한지 다시 한번 확인해주세요.") date = None return date # 22-09-06 : 코드의 존재 여부를 확인하는 메서드 추가 def set_code(self, code, cd=None): if cd != None: cd = ConnectDB() # db 연결 클래스 생성 if code == '': print(f"올바른 제품코드를 입력해 주세요") find_rows = None else: sql = "select * from product where pCode =" + f"'{code}'" find_rows = cd.db_find_all(sql, "제품명 개별 조회 오류입니다.") if not(find_rows) : find_rows = None return find_rows # set_code는 메서드 자체로 쓰여지지 않고 어디선가 호출되어 사용되므로 # 여기서 db 연결 객체를 소멸시키지 않는다 class UserInput: # 사용자 입력 함수 # None이 아닌 값이 리턴될 때까지 반복해서 입력받음 def input_product(self): if1 = InputFilter() while True: in_pname = if1.set_pname(input("제품 이름을 입력하세요 : ")) if in_pname : break else: continue # while True: in_uprice = if1.set_uprice(input("가격을 입력하세요 : ")) if in_uprice: break else: continue # while True: in_drate = if1.set_drate(input("할인율을 입력하세요 : ")) if in_drate : break else: continue # return in_pname, in_uprice, in_drate def input_sales(self): if1 = InputFilter() # 필터링 클래스 생성 while True: in_qty = if1.set_qty(input("판매 수량을 입력하세요 : ")) if in_qty : break else: continue # while True: in_date = if1.set_date(input("날짜를 0000-00-00 00:00:00 형식으로 입력하세요 : ")) if in_date : break else : continue return in_qty, in_date class Insert: # 22-09-07 : 타겟 테이블 지정 전역변수, 생성자 삭제 # 22-09-07 : Find 클래스 대신 ConnectDB 활용한 코드로 변경 def insert_product(self, in_pCode='', rows=None): # 22-09-06 : Find 클래스 대신 ConnectDB 활용한 코드로 변경 if1 = InputFilter() ui1 = UserInput() cd1 = ConnectDB() print("\n<<<제품 등록입니다>>>") if in_pCode == '': in_pCode = input("등록할 제품코드를 입력하세요 : ") rows = if1.set_code(in_pCode, cd1) # ConnectDB 생성됨 if rows != None : # product 테이블에 존재하는 pCode일 경우 print("이미 존재합니다. 다른 제품코드를 입력하세요") else : iValue = ui1.input_product() # input_product의 리턴값은 3개이므로 iValue의 요소는 3개 # sql = f"""insert into product values('{in_pCode}','{iValue[0]}', '{iValue[1]}', '{iValue[2]}')""" cd1.db_commit(sql, "제품 수정에 실패했습니다.") # db에 반영 print("\n제품 등록을 성공했습니다.") print() del cd1 # ConnectDB 객체 소멸시킴 def insert_sales(self, in_sCode='', rows=None): if1 = InputFilter() cd1 = ConnectDB() print(f"\n<<<판매 등록입니다>>>") if in_sCode == '': in_sCode = input("등록할 제품코드를 입력하세요 : ") rows = if1.set_code(in_sCode, cd1) # 제품코드 유효성 체크 if rows == None : # product 테이블에 존재하지 않는 sCode일 경우 print("조회결과 입력한 코드에 맞는 제품이 없습니다.") yesNo = input('제품을 추가하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 print('제품을 추가로 등록합니다.') self.insert_product(in_sCode, rows) # 추가 등록 후 다시 판매 등록 print('<<<판매 등록입니다>>>') self.insert_sales(in_sCode, rows) else : print("판매등록을 종료합니다.") else: ui1 = UserInput() iValue = ui1.input_sales() # sql = f"""insert into sales(sCode, sDate, Qty, Amt) select '{in_sCode}', '{iValue[1]}', '{iValue[0]}', {iValue[0]} * unitPrice from product where pCode = '{in_sCode}';""" # 서브쿼리를 활용하여 product 테이블의 unitprice값을 가져옴 cd1.db_commit(sql, "판매 등록에 실패했습니다.") print("\n판매 등록을 성공했습니다.") print() del cd1 # ConnectDB 소멸 class Update: # 22-09-07 : 타겟 테이블 지정 전역변수, 생성자 삭제 # 22-09-07 : Find 클래스 대신 ConnectDB 활용한 코드로 변경 def update_product(self): st1 = ShowTables() if1 = InputFilter() ui1 = UserInput() cd1 = ConnectDB() print(f"<<<제품 목록 조회입니다>>>") sql = "select * from product" # 테이블 전체 조회 rows = cd1.db_find_all(sql, "제품 목록 조회에 실패했습니다.") st1.print_product(rows) in_pCode = input("수정할 제품코드를 입력하세요 : ") rows = if1.set_code(in_pCode, cd1) # 제품코드 유효성 체크 if rows == None: # 입력받은 코드가 제품 테이블에 없을 경우 print("조회결과 입력한 코드에 맞는 제품이 없습니다.") # else : # select 쿼리 실행결과가 있는 경우 print("\n<<<제품코드 조회결과입니다>>>") st1.print_product(rows) yesNo = input('수정하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 print("<<<수정할 내용을 입력하세요.>>>") iValue = ui1.input_product() # 사용자 입력 sql = f"update product set pName = '{iValue[0]}', unitPrice ='{iValue[1]}', discountRate='{iValue[2]}' where pCode = '{in_pCode}'" cd1.db_commit(sql, "제품 수정에 실패했습니다.") # db에 쿼리 반영 print("<<<수정을 완료했습니다>>>") print("\n<<<수정 결과입니다>>>") sql = "select * from product where pCode =" + f"'{in_pCode}'" # 수정한 레코드만 가져옴 st1.print_product(cd1.db_find_all(sql, "수정 결과를 출력할 수 없습니다.")) else: print("<<<수정을 취소했습니다.>>>") del cd1 # ConnectDB 소멸(close) def update_sales(self): ls_seqNo = [] st1 = ShowTables() if1 = InputFilter() ui1 = UserInput() cd1 = ConnectDB() print(f"<<<판매 목록 조회입니다>>>") sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" rows = cd1.db_find_all(sql, "판매 목록 조회에 실패했습니다.") st1.print_sales_pname(rows) print(f'\n<<<판매 수정입니다>>>') in_sCode = input("수정할 제품코드를 입력하세요 : ") rows = if1.set_code(in_sCode, cd1) # 제품코드 유효성 체크 if rows == None: # 입력받은 코드가 판매 테이블에 없을 경우 print("조회결과 입력한 코드에 맞는 판매가 없습니다.") # else: print("\n<<<제품코드 조회결과입니다>>>") sql = "select * from sales where sCode = "+f"'{in_sCode}'" rows = cd1.db_find_all(sql) st1.print_sales(rows) for row in rows: ls_seqNo.append(row[0]) # 아래 if문을 if int(i_seqNo) in ls_seqno:로 수정할 경우 # int값이 아닌 값을 입력받았을 때 예외처리를 추가로 해주어야 함. # 그래서 str(row[0])으로 리스트 내부 값들을 str형으로 변환할 필요가 있음. ### <요구사항-6> 반영### ls_seqNo = list(map(str, ls_seqNo)) # 22-09-08 : map 함수를 활용하여 str로 형변환 # 입력받은 i_seqNo와 비교하기 위해 리스트 요소 모두를 str로 형변환 i_seqNo = input("수정할 판매번호를 입력하세요 : ") # sales 테이블의 primary key는 (seqNo, sCode)이므로 seqNo 또한 입력받음. if i_seqNo in ls_seqNo: yesNo = input('수정하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 print("<<<수정할 내용을 입력하세요.>>>") iValue = ui1.input_sales() sql = f"""update sales set sDate = '{iValue[1]}', Qty = '{iValue[0]}', Amt ='{iValue[0]}' * (select unitPrice from product where pCode='{in_sCode}') where seqNo = '{i_seqNo}' and sCode = '{in_sCode}'""" # 서브쿼리를 활용하여 product테이블의 unitprice데이터를 가져옴 cd1.db_commit(sql, "판매 수정에 실패했습니다.") print("<<<수정을 완료했습니다>>>") print("\n<<<수정 결과입니다>>>") sql = "select * from sales where sCode =" + f"'{in_sCode}'" + " and seqNo = " + f"'{i_seqNo}'" st1.print_sales(cd1.db_find_all(sql, "수정 결과 조회에 실패했습니다.")) else: print("<<<수정을 취소했습니다.>>>") else: print("<<<없는 판매번호입니다. 수정을 종료합니다.>>>") del cd1 class Delete: # 22-09-07 : 타겟 테이블 지정 전역변수, 생성자 삭제 # 22-09-07 : Find 클래스 대신 ConnectDB 활용한 코드로 변경 def delete_product(self): st1 = ShowTables() if1 = InputFilter() cd1 = ConnectDB() print("<<<상품 목록 조회입니다>>>") sql = "select * from product" rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.") st1.print_product(rows) in_pCode = input("삭제할 제품코드를 입력하세요 : ") rows = if1.set_code(in_pCode, cd1) if rows == None : print(f"조회결과 입력한 코드에 맞는 제품이 없습니다.") # else : yesNo = input('삭제하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 sql = f"delete from product where pCode = '{in_pCode}'" cd1.db_commit(sql, "제품 삭제에 실패했습니다.") print('삭제 성공했습니다.') print("\n<<<목록 조회입니다>>>") sql = "select * from product" rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.") st1.print_product(rows) else : print("<<<삭제를 취소했습니다.>>>") del cd1 # close def delete_sales(self): st1 = ShowTables() if1 = InputFilter() cd1 = ConnectDB() ls_seqNo = [] print("<<<판매 목록 조회입니다>>>") sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" rows = cd1.db_find_all(sql, "전체 목록 조회 오류입니다.") st1.print_sales_pname(rows) in_sCode = input("삭제할 제품코드를 입력하세요 : ") rows = if1.set_code(in_sCode, cd1) if rows == None : print(f"조회결과 입력한 코드에 맞는 판매가 없습니다.") # else : print("\n<<<제품코드 조회결과입니다>>>") sql = "select * from sales where sCode="+f"'{in_sCode}'" rows = cd1.db_find_all(sql) st1.print_sales(rows) for row in rows: ls_seqNo.append(str(row[0])) i_seqNo = input("삭제할 판매번호를 입력하세요 : ") if i_seqNo in ls_seqNo: yesNo = input('삭제하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 sql = f"delete from sales where sCode = '{in_sCode}' and seqNo = '{i_seqNo}'" cd1.db_commit(sql, "판매 삭제에 실패했습니다.") print('삭제 성공했습니다.') sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" print("\n<<<목록 조회입니다>>>") rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.") st1.print_sales_pname(rows) else : print("<<<삭제를 취소했습니다.>>>") else : print("<<<없는 판매번호입니다. 삭제를 종료합니다.>>>") del cd1 class Reset: # update 테이블과 거의 유사한 구조이지만, 코드 가독성 향상과 # 기능별 분리를 위해 별도의 클래스로 분리함. target = '' target_table = '' def __init__(self, target): self.target = target if self.target == 'p': self.target_table = 'product' else : self.target_table = 'sales' def reset(self): st1 = ShowTables() cd1 = ConnectDB() sql = f"select * from {self.target_table}" find_rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.") if find_rows : if self.target == 'p' : st1.print_product(find_rows) else : st1.print_sales(find_rows) print(f'\n<<<{self.target_table}테이블 초기화입니다>>>') yesNo = input('모두 삭제하고 초기화 하시겠습니까?(y/n) : ') if yesNo.upper() == "Y": # 22-09-08 : 기존엔 Y or y로 체크했으나 upper 함수로 대문자화하여 체크 #sql = f"delete from {self.target_name}" # 22-08-29 truncate로 바꿈으로서 sales 테이블 seqNo 별도 초기화 필요 없어짐 sql = f"truncate table {self.target_table}" cd1.db_commit(sql, "초기화에 실패했습니다.") print("초기화 성공했습니다.") else : print("<<<초기화를 취소했습니다.>>>") else : print("삭제할 데이터가 없습니다.") print("<<<초기화를 취소합니다.>>>") del cd1 if __name__ == "__main__" : while True: create_table() os.system('cls') print("-----제품관리----- | -----판매관리-----") print("제품 등록 : 01 | 판매 등록 : 11 ") print("제품목록 조회 : 02 | 판매목록 조회 : 12 ") print("코드별 조회 : 03 | 코드별 조회 : 13 ") print("제품명별 조회 : 04 | 제품명별 조회 : 14 ") print("제품 수정 : 05 | 판매 수정 : 15 ") print("제품 삭제 : 06 | 판매 삭제 : 16 ") print("테이블 초기화 : 07 | 테이블 초기화 : 17 ") print(" | 외부파일 등록 : 18 ") print(" | 시각화 출력 : 19 ") print('----------------------------------------------') print("관리 종료 : 00 ") print('----------------------------------------------') print() sel = input("작업을 선택하세요 : ") print() if sel == '01' : p1 = Insert() p1.insert_product() os.system("pause") elif sel == '02' : p2 = Read('p') p2.read_all() os.system("pause") elif sel == '03' : p3 = Read('p') p3.read_code() os.system("pause") elif sel == '04' : p4 = Read('p') p4.read_name() os.system("pause") elif sel == '05' : p5 = Update() p5.update_product() os.system("pause") elif sel == '06' : p6 = Delete() p6.delete_product() os.system("pause") elif sel == '07' : p7 = Reset('p') p7.reset() os.system("pause") # elif sel == '11' : s1 = Insert() s1.insert_sales() os.system("pause") elif sel == '12' : s2 = Read('s') s2.read_all() os.system("pause") elif sel == '13' : s3 = Read('s') s3.read_code() os.system("pause") elif sel == '14' : s4 = Read('s') s4.read_name() os.system("pause") elif sel == '15' : s5 = Update() s5.update_sales() os.system("pause") elif sel == '16' : s6 = Delete() s6.delete_sales() os.system("pause") elif sel == '17' : s7 = Reset('s') s7.reset() os.system("pause") elif sel == '18' : s8 = FileInsert('s') os.system("pause") elif sel == '19' : s0 = ShowGraphs('s') os.system("pause") # elif sel == '00' : print("직원관리를 종료합니다. ") os.system("pause") os.system('cls') sys.exit(0) else : print("잘못 선택했습니다. ") os.system("pause") | cs |
- DBController.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import pymysql # MySQL데이터베이스를 사용하기 위한 라이브러리를 등록함 config = { # MySQL데이터베이스를 사용하기 위해 환경변수를 딕셔너리로 생성함. 'host' : '127.0.0.1', # MySql 이 동작하는 ipv4주소 'user' : 'root', # MySql 설치할 때 정한 계정 'passwd' : 'root1234', # MySql 설치할 때 정한 비밀코드 'database' : 'test_db', # MySql 설치할 때 처음 생성한 데이터베이스 'port' : 3306, # MySql이 응용프로그램과 통신할 때 사용하는 포트코드 리터럴이 아닌 정수값으로 써야함 'charset' : 'utf8', # 한글을 사용하겠다는 설정 'use_unicode' : True # 한글을 사용하겠다는 설정 } # 22-09-06 : db_connection 함수를 클래스로 변경 class ConnectDB: conn, cursor = None, None def __init__(self) : try: self.conn = pymysql.connect(**config) self.cursor = self.conn.cursor() except Exception : print("데이터베이스 연동 실패") def db_commit(self, sql, error_msg=''): try: self.cursor.execute(sql) self.conn.commit() except Exception as e: if error_msg == '': error_msg = "db연동실패 : "+ str(e) print(error_msg) self.conn.rollback() def db_find_all(self, sql, error_msg=''): try: self.cursor.execute(sql) rows = self.cursor.fetchall() except Exception as e: if error_msg == '': error_msg = "db연동실패 : "+ str(e) print(error_msg) self.conn.rollback() return rows def db_find_one(self, sql, error_msg=''): try: self.cursor.execute(sql) rows = self.cursor.fetchone() except Exception as e: if error_msg == '': error_msg = "db연동실패 : "+ str(e) print(error_msg) self.conn.rollback() return rows def __del__(self): self.cursor.close() self.conn.close() | cs |
- FileController.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | import datetime from DBController import * class FileRW : def read_file(self, file_name): file_name = "data/"+file_name try: tf1 = open(file_name, mode='r', encoding='utf-8') # 파일을 읽기 모드로 열고, 한글이 깨지지 않도록 utf-8로 인코딩 full_text = [text.strip('\n').split(',') for text in tf1.readlines()] # 22-09-08 : 향상된 for문으로 수정 #full_text = tf1.readlines() # 파일을 한줄씩 읽어 list변수 full_text에 저장 #for i in range(len(full_text)): #full_text[i] = full_text[i].strip() # 파일 내용의 맨 앞과 맨 뒤의 공백을 제거함 #full_text[i] = full_text[i].split(',') # 콤마를 기준으로 분리하여 2차원 리스트로 저장 tf1.close() return full_text except Exception : # 예외 발생시 파일명 오류 안내 print('없는 파일명입니다. 확장자를 잊지는 않으셨나요?') full_text = False finally : return full_text def write_file(self, file_name, rows): file_name = "data/"+file_name try: tf1 = open(file_name, mode='w', encoding='utf-8') # 파일을 읽기 모드로 열고, 한글이 깨지지 않도록 utf-8로 인코딩 for row in rows: ### <요구사항-4> 반영 ### # 요구사항을 반영할만한 이중 포문이 없어 향상된 for문으로 대체합니다. text = ','.join(str(i) for i in row) # 각 요소를 str형으로 변환한 후 ,를 구분자로 하여 한줄로 만듦 tf1.write(text + '\n') # 파일에 쓰기 except Exception as e : print('파일 쓰기 중 에러가 발생했습니다.') finally : tf1.close() class FileFilter: content = [] pop = 0 def filter_code(self, content, cd): ls_code = [] rm_code = [] if cd == '' : cd = ConnectDB() for i in range(len(content)): ls_code.append(content[i][0]) # 코드 컬럼만 리스트로 만듦 for code in ls_code : sql = "select * from product where pCode =" + f"'{code}'" row = cd.db_find_one(sql, "테이블 조회에 실패했습니다.") # product 테이블에 존재하는지만 확인하면 되므로 한줄만 읽어옴 if row == None: rm_code.append(ls_code.index(code)) # 지워야 하는 코드의 인덱스를 리스트 rm_code에 저장 pop = 0 # 삭제 후 인덱스를 조정해주기 위한 변수 if rm_code : for i in rm_code : del content[i-pop] pop = pop+1 # 삭제 대상 인덱스 삭제 후 뒤의 항목들은 # 인덱스가 1씩 감소하기 때문에 pop을 증가시켜 인덱스에서 마이너스해준다. return content def filter_date(self, content, content_type): # 22-09-07 : filter_table_date와 filter_file_date 메서드 통합 ls_date = [] rm_date = [] if content_type == 'file' : for i in range(len(content)): # 날짜 컬럼만 추출해서 리스트에 저장 ls_date.append(content[i][1]) for date in ls_date: try: str_date = date[0:4] + '-' + date[4:6] + '-' + date[6:8] datetime.datetime.strptime(str_date, "%Y-%m-%d") except Exception as e : # 존재 가능한 날짜가 아닐 경우 rm_date.append(ls_date.index(date)) # 지워야 하는 날짜의 인덱스를 리스트 rm_date에 저장 # else : # table for i in range(len(content)): # 날짜 컬럼만 추출해서 리스트에 저장 ls_date.append(content[i][2]) for i in range(len(ls_date)): try: datetime.datetime.strptime(ls_date[i], '%Y-%m-%d %H:%M:%S') content[i][2] = ls_date[i][0:10] # 리스트에는 시간을 제외한 날짜만 저장되도록 함 except Exception as e : # 존재 가능한 날짜가 아닐 경우 rm_date.append(i) # 지워야 하는 날짜의 인덱스를 리스트 rm_date에 저장 if rm_date : pop = 0 for i in rm_date : del content[i-pop] pop = pop+1 # 삭제 대상 인덱스 삭제 후 뒤의 항목들은 # 인덱스가 1씩 감소하기 때문에 pop을 증가시켜 인덱스에서 마이너스해준다. return content def filter_amt(self, content, cd): if cd == '' : cd = ConnectDB() # 매개변수로 전달된 connectDB 객체가 없을 경우 생성 for con in content: sql = f"select unitPrice from product where pCode = '{con[1]}'" price = cd.db_find_one(sql, 'product 테이블의 unitprice 조회에 실패했습니다.')[0] if float(con[4]) != float(int(con[3]) * price): con[4] = int(con[3]) * price # 곱의 결과가 리스트 내부의 amt(con[4])와 같지 않을 경우 # con[4]에 곱한 결과를 덮어씌움 return content class FileInsert: target = '' target_name = '' file_name = '' def __init__(self, target): self.target = target if target == 's' : self.target_name == '제품' else : self.target_name = '판매' self.file_insert() def file_insert(self): fr1 = FileRW() ff1 = FileFilter() cd1 = ConnectDB() print(f'\n<<<{self.target_name}테이블에 외부 파일 등록입니다>>>') self.file_name = input("data 폴더 내부에 있는 파일명을 입력하세요 : ") content = fr1.read_file(self.file_name) if content == False: print('<<<외부 파일 등록을 종료합니다>>>') else : lines = ff1.filter_code(content, cd1) lines = ff1.filter_date(lines, 'file') lines = self.set_amt(lines, cd1) self.write_table(lines) print('<<<테이블에 등록이 완료되었습니다.>>>') del cd1 def set_amt(self, content, cd=''): if cd=='' : cd = ConnectDB() for line in content : sql = "select * from product where pCode =" + f"'{line[0]}'" row = cd.db_find_one(sql) if len(line) > 3: # 인덱스3 (가격)이 이미 있다면 지워줌 del line[3] line.append(int(row[2]) * int(line[2])) # 각 항목의 제품코드를 활용하여 product 테이블에서 unitPrice를 가져와 # qty(인덱스2)와 곱하여 리스트 각 항목 끝에 삽입한다. return content def write_table(self, full_text, cd=''): if cd=='' : cd = ConnectDB() for text in full_text: date = text[1][0:4] + '-' + text[1][4:6] + '-' + text[1][6:8] date = datetime.datetime.strptime(date, '%Y-%m-%d') sql = f"""insert into sales(sCode, sDate, Qty, Amt) values ('{text[0]}', '{date}', '{text[2]}', '{text[3]}')""" cd.db_commit(sql, "테이블 쓰기에 실패했습니다.") | cs |
- ShowGraph.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | from FileController import * from DBController import * import pandas as pd # dataframe을 사용하기 위함 import matplotlib.pyplot as plt # 그래프 세부설정 및 팝업창 출력을 위함 import re # 정규식으로 문자를 필터링하기 위함 class ShowGraphs: target = '' target_name = '' def __init__(self, target): self.target = target if target == 's' : self.target_name == '제품' else : self.target_name = '판매' self.show_amt_graph() def show_amt_graph(self): fr1 = FileRW() ff1 = FileFilter() cd1 = ConnectDB() # DB connect sql = "select * from sales" rows = cd1.db_find_all(sql) # 테이블 전체를 읽어서 fr1.write_file('sales_all.txt', rows) content = fr1.read_file('sales_all.txt') # 파일을 다시 읽어옴. lines = ff1.filter_date(content, 'table') # 날짜 필터링 lines = ff1.filter_amt(lines, cd1) # amt 필터링 lines = self.add_column(lines, 'pName', 2, cd1) # 리스트에 pName 추가 lines = self.add_column(lines, 'unitPrice', 5, cd1) # 리스트에 unitPrice 추가 column_names = ['seqNo', 'pCode', 'pName', 'date', 'qty', 'unitPrice', 'amt'] df = pd.DataFrame(lines, columns=column_names) # 데이터프레임 생성 df = df.set_index('date') df['amt'] = pd.to_numeric(df['amt']) # 문자인 amt 컬럼을 숫자로 변경 self.create_graph(df, 'date') self.create_graph(df, 'pName') del cd1 # DB close def add_column(self, content, col_name, location, cd=''): if cd=='' : cd = ConnectDB() for con in content: sql = f"select {col_name} from product where pCode = '{con[1]}'" data = str(cd.db_find_one(sql)) data = re.sub("['(),]", '', data) # re.sub 메서드를 통해 데이터 주변의 문자 제거 con.insert(location, str(data)) # 특정 위치에 조회한 값 삽입 return content def create_graph(self, df, group_col_name): sub_df = pd.DataFrame() plt.rc('font', family='Malgun Gothic') # 문자 출력을 위한 폰트 지정 (현재 : 맑은고딕) if group_col_name == 'date': sub_df['amt'] = df.amt # 인덱스와 amt 컬럼을 가진 df_day 데이터프레임 생성 sub_df = sub_df.groupby(group_col_name).sum() # 날짜별 합계를 데이터프레임으로 저장 sub_df.plot.line(figsize=(10, 5)) # 라인 그래프 plt.xlabel('date') # x축 라벨 plt.legend(['total amount']) # 범례 else : sub_df[group_col_name] = df[group_col_name] sub_df['amt'] = df.amt sub_df = sub_df.groupby(group_col_name).sum() # 날짜별 합계를 데이터프레임으로 저장 sub_df = sub_df.sort_values('amt', ascending=False) # 총액이 낮은순으로 정렬 sub_df.plot.barh(figsize=(10, 5)) plt.xlabel('total amount') plt.ylabel(group_col_name) path = 'data/'+group_col_name+'.png' # 파일명 지정 plt.savefig(path) # 파일로 저장 plt.show() # 팝업창으로 출력 def filter_amt(self, content, cd): # 파일의 amt값이 올바른지 확인하는 메서드 # 기존에 FileContoller 파일에 존재하는 코드였다. # 22-09-08 : 그래프 출력 전 amt값의 유효성을 확인하는 메서드이기 때문에 ShowGraphs클래스로 이동했다. if cd == '' : cd = ConnectDB() # 매개변수로 전달된 connectDB 객체가 없을 경우 생성 for con in content: sql = f"select unitPrice from product where pCode = '{con[1]}'" price = cd.db_find_one(sql, 'product 테이블의 unitprice 조회에 실패했습니다.')[0] if float(con[4]) != float(int(con[3]) * price): con[4] = int(con[3]) * price # 곱의 결과가 리스트 내부의 amt(con[4])와 같지 않을 경우 # con[4]에 곱한 결과를 덮어씌운다. return content | cs |
'web project' 카테고리의 다른 글
제품&판매 관리 시스템 : 삭제, 수정 히스토리 테이블 생성 및 관리 (0) | 2022.10.05 |
---|---|
제품&판매 관리 시스템 : 포트폴리오 수정, 시스템 관련 질답 (0) | 2022.10.05 |
제품&판매 관리 시스템 : change log 작성, 포트폴리오 ppt (0) | 2022.10.04 |
제품&판매 관리 시스템 : 테이블 초기화, 파일 읽기, 테스트케이스 작성 (0) | 2022.09.30 |
제품&판매 관리 시스템 : 테이블 생성, 체크리스트, 1차 코드 (0) | 2022.09.29 |
댓글