본문 바로가기
web project

제품&판매 관리 시스템 : 삭제, 수정 히스토리 테이블 생성 및 관리

by kuah_ 2022. 10. 5.

 

 

 

[ 운영상 이슈 1 ]

2022.09.27 ~ 2022.09.30

<product_history 테이블 생성>

1
2
3
4
5
6
7
8
9
10
11
12
13
create table product_history(
    rowNo int(10not null auto_increment
    pCode varchar(4),    
    pName varchar(20not null,
    unitPrice int not null,
    discountRate DECIMAL(52NOT NULL DEFAULT 1.0,
    validFrom datetime NOT NULL default now(),
    validUntil datetime NOT NULL default '9999-12-31 23:59:59',
    primary key(rowNo)
);
 
-- datetime 범위 :  '1000-01-01 00:00:00 ~ 9999-12-31 23:59:59'
-- timestamp  : '1970-01-01 00:00:00 ~ 2037-12-31 23:59:59'
cs

- 'history table example' 키워드로 구글링하여 보편적인 형태로 컬럼을 구성하였다.

- product 테이블과 같은 컬럼(제품코드, 제품명, 단가, 할인율)과 시작일, 종료일, row번호 컬럼을 가지고 있다.

- insert, update, delete 등 수행 항목을 별도의 컬럼으로 생성하지 않고 시작일-종료일으로만 파악한다.

- 과거부터 현재까지 데이터를 보관함으로써 기록의 역할을 하고, 별도의 자료나 통계를 생성할 수 있다.

 

 

 

<요구사항>

A. 제품테이블(product )에 로우가 생성(제품등록)되거나 변경(제품수정)되는 상황이 발생하면
    해당 내용을 백업의 개념으로 보관하는 product_history테이블에 새로운 로우가 추가되도록 구현

 

 

B. 제품관리 시스템에서 제품정보의 등록, 제품정보의 수정, 제품정보의 삭제 기능이 수행되면
    product_history테이블에 로우가 추가되도록 처리되는 기능을 구현
    단, 이 기능은 함수(또는 클래스)를 만들어 처리

 

 

C. product_history 테이블은 다음과 같은 처리를 할 수 있음

    - product 테이블에 로우의 생성(Insert), 수정(Update), 삭제(Delete) 의 세 개의 동작이 발생할 때마다
      해당 동작을 구체적으로 기록(저장, Insert)하여 다른 시스템이나, 프로그램, 로직에서 활용할 수 있어야 함

 

 

D. 초기화 메뉴 개선
    1. 제품관리 시스템의 메뉴에서 '제품초기화' 라는 메뉴의 선택 번호를 누르면
        제품테이블(product)이 생성(초기화) 되면서 정보 10개가 insert되어야 함

    2. 제품관리 시스템의 메뉴에서 '제품초기화' 라는 메뉴의 선택 번호를 누르면
        1의 기능을 수행함과 동시에 product_history 테이블도 생성(초기화)되면서
        제품테이블의 로우가 생성(insert) 되었을 때 동작하는 규칙에 의해 product_history 테이블의 로우도 자동 생성

    3. 판매관리 시스템의 메뉴에서 '판매초기화' 라는 메뉴의 선택 번호를 누르면

        판매테이블(sales)이 생성(초기화) 되면서 정보 35개가 insert되어야 함
        

 

 

2022.09.29

<신기능 프로그램>

1. 판매조회(코드별-세무자료용) : 역대 가장 낮은 단가를 sales 테이블의 모든 레코드에 적용

2. 판매조회(코드별-주주총회용) : 역대 가장 높은 단가를 sales 테이블의 모든 레코드에 적용

 

 

 

<요구사항>

A. 제품 등록 (제품관리시스템 이용)

    1. (a020/이공마우스/2000/1.0) 정보 등록

    2. (a030/삼공키보드/3000/1.0) 정보 등록

 

 

B. 판매 등록 (판매관리시스템 이용)

    1. (a020/1000) 정보 등록

    2. (a030/2000) 정보 등록

 

 

C. 판매관리시스템의 코드별 조회 기능에서 판매금액합계를 출력하도록 수정

 

 

D. 제품관리시스템의 제품등록 기능을 이용하여 a030/삼공키보드/3000/1.0 의 정보 중, 단가를 3,300으로 변경
    판매관리시스템의 판매등록 기능을 이용하여 a030 제품을 2,000개 등록

 

 

E. 판매조회(코드별-세무자료용) 메뉴 신설

    1. sales 테이블의 로우 중에서 사용자가 입력한 제품코드에 해당하는 로우를 모두 출력

    2. 모든 로우의 판매금액 합계를 출력

    3. 판매금액은 product_history 테이블의 해당 제품 코드와 같은 로우들 중에서 가장 낮은 단가를 적용하여 계산

 

    

F. 판매조회(코드별-주주총회용) 메뉴 신설

    1. sales 테이블의 로우 중에서 사용자가 입력한 제품코드에 해당하는 로우를 모두 출력

    2. 모든 로우의 판매금액 합계를 출력

    3. 판매금액은 product_history 테이블의 해당 제품 코드와 같은 로우들 중에서 가장 높은 단가를 적용하여 계산

 

 

G. 제품관리 시스템과 판매관리 시스템의 모든 조회기능을 구현할 때 천단위 컴마기능 적용

 

 

 

<구현 결과>

1. 판매관리시스템의 코드별 조회 기능 (요구사항 C)

 

 

2. 판매조회(코드별-세무자료용) 메뉴

 

 

3. 판매조회(코드별-주주총회용) 메뉴

 

 

 

<코드 비교분석>

- 판매조회(코드별-세무자료용)와 판매조회(코드별-주주총회용)을 비교

- 비교되는 내용이 지그재그가 되지 않게 한 행으로 맞춰야 함

- 넘버링도 양쪽이 대응되도록 하며, 전체적으로 균형을 이룰 것

https://docs.google.com/document/d/1da8gataaWFVY019TCWtLT2OulU55OjnDt0Cd-bRVFXk/edit?usp=sharing 

 

코드비교분석_220930

<코드비교분석> 개요 : 판매 관리 시스템의 코드별 조회 기능을 세분화하여 세무자료용 조회와 주주총회용 조회 두가지 메뉴를 추가했습니다. 사전에 DBMS에서 product 테이블의 수정 내역을 기록

docs.google.com

 

 

 

<완성 코드>

- main.py와 DBController.py만 수정됨

- https://drive.google.com/file/d/1aI5ZKJwKWYHjOWnNSc6q96pgRuF6CslH/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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
import os
import sys
import datetime # 날짜 유효성 검사 위함
 
### <요구사항-2> 반영 ###
# 22-09-05 : 파일 분리
# 그래프, 파일, DB 즉 외부에서 데이터를 얻어오는 기능별로 파일을 분리하고, import하여 사용한다.
# main.py는 메인 파일로, 메뉴 및 CRUD 기능의 진행을 구현했다.
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) # 문자 폭을 맞춰서 정렬한 길이(length)
    s = w-# s = 사용자 지정 범위 - 출력할 데이터
    if s <= 0:
        return x
    if align == 'l'# left
        return x + ' '*+ '| ' 
        # 공백 끝마다 구분선 '| '을 추가하여 컬럼간 구분선을 표시한다.
    if align == 'c'# center
        # 현재 코드에서 사용되지는 않지만 추후 코드 추가 시 사용 가능성이 있어 포함했다.
        sl = s//2
        sr = s - sl
        return ' '*sl + x + ' '*sr
    return ' '*+ 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 # 클래스 소멸(connection close)
        
### <요구사항-3> 반영 - 함수와 클래스 사용 ###
class ShowTables:
# 리스트(테이블)을 출력하는 함수. 
# 테이블별로 출력문이 반복되기 때문에 각각 메서드를 작성하여 클래스로 추합했다.
# 출력문을 함수로 선언함으로서, 컬럼명이 변경되거나 추가되더라도 전체 코드에서 찾아서 수정하지 않고
# 함수만 추가 또는 수정하면 된다.
    
    def print_product(self, rows): # 제품 테이블(pCode, pName, UnitPrice, discountRate)
        print('{}{}{}{}'.format(fmt('pCode'10), fmt('pName'20), fmt('UnitPrice'12), 'discountRate'))
        # fmt 함수를 이용하여 한글을 출력해도 일정한 간격으로 테이블이 출력되도록 했다.
        print('-'*62# 컬럼명과 데이터간 구분선
        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): # 판매 테이블(seqNo, sCode, sDate, Qty, Amt)
        # 22-09-29 : 숫자에 콤마 출력되도록 수정
        print('{}{}{}{}{}'.format(fmt('seqNo'6), fmt('sCode'6), fmt('sDate'20),fmt('Qty'6), 'Amt'))
        print('-'*62)
        for row in rows :
            print("{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20)))
            print(fmt("{0:,}".format(row[3]), 6), fmt("{0:,.2f}".format(row[4]), 14'r'), sep='')
 
    def print_sales_pname(self, rows): # 판매테이블과 제품테이블 join 결과(seqNo, sCode, pName, sDate, Qty, Amt)
        # 22-09-29 : 숫자에 콤마 출력되도록 수정
        print('{}{}{}{}{}{}'.format(fmt('seqNo'6), fmt('sCode'6), fmt('pName'20), fmt('sDate'20), fmt('Qty'6), 'Amt'))
        print('-'*82)
        for row in rows :
            print("{}{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20), fmt(row[3], 20)), end='')
            print(fmt("{0:,}".format(row[4]), 6), fmt("{0:,.2f}".format(row[5]), 14'r'), sep='')
 
# 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> 반영 - zip 함수 사용 ###        
        # 22-09-08 : if문으로 p, s를 구분하여 쿼리문을 지정하지 않고 딕셔너리 키값(p,s)에 따라 쿼리문을 지정한다.
        table_read_sql = dict(zip(tables, read_sql)) # 각 테이블에 해당하는 sql을 딕셔너리로 생성
        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 # ConnectDB 클래스 소멸
 
    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;"""
                # product 테이블과 sales 테이블을 inner join
                # product에 존재하지 않는 code를 가진 레코드는 출력될 필요가 없어서 inner join했다.
        rows = cd1.db_find_all(sql, "전체 목록 조회 오류입니다."
 
        if rows:
            print('\n<<<전체 목록 조회>>>')
            if self.target == 'p': st1.print_product(rows)
            else : st1.print_sales_pname(rows)
            
            # read_all()메서드에서 <요구사항 - 5>를 반영하기 전 코드와 매우 유사
            # 딕셔너리를 생성하지 않고 if문으로 target에 따라 각각의 코드를 실행한다.
            print('\n<<<개별 조회(코드)입니다>>>')
            in_Code = input('조회할 코드를 입력하세요 : ')
            if self.target == 'p'
            # target에 따라 실행될 sql을 다르게 저장한다.
                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 S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt 
                from sales S, product P where S.sCode = P.pCode and S.sCode = """ + f"'{in_Code}'"
                rows = cd1.db_find_all(sql, "판매코드 개별 조회 오류입니다.")
                if rows: 
                    # 22-09-29 : 판매 금액 합계 출력 추가
                    st1.print_sales_pname(rows)
                    print('-'*82)
                    amttotal = 0
                    for row in rows:
                        amttotal = amttotal + row[5]
                    print("{}".format(fmt("판매금액합계"66)), end='')
                    print(fmt("{0:,}".format(amttotal), 14'r'))
                else : 
                    print("입력하신 코드에 해당하는 판매가 없습니다.")
 
        del cd1 # 클래스 소멸
 
    def read_name(self):
    # read_code 메서드와 거의 유사하여 합칠 수도 있지만,
    # 기능별로 함수가 분리되어 있는 편이 가독성과
    # 함수 호출의 편리성이 향상되어 메서드를 분리했다.
        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;"
            # 테이블 inner join 후 입력한 제품명이 있는 레코드를 조회하는 쿼리
            rows = cd1.db_find_all(sql, "제품명 개별 조회 오류입니다."
            if rows: st1.print_sales(rows)
            else : print("입력하신 제품명에 해당하는 판매가 없습니다.")
 
        del cd1 # 클래스 소멸
 
    def read_code_sales(self, subject):
        # 22-09-29 생성 : history테이블의 최소값을 곱하여 세무자료를 만든다.
        cd1 = ConnectDB() # 클래스 생성
        st1 = ShowTables()
        subjects = {'min':'세무자료용''max':'주주총회용'}
        
        sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt 
                from sales S, product P where S.sCode = P.pCode;"""
                # product 테이블과 sales 테이블을 inner join
                # product에 존재하지 않는 code를 가진 레코드는 출력될 필요가 없어서 inner join했다.
        rows = cd1.db_find_all(sql, "전체 목록 조회 오류입니다."
 
        if rows:
            print('\n<<<전체 목록 조회>>>')
            st1.print_sales_pname(rows)
            
            in_Code = input('조회할 코드를 입력하세요 : ')
            print('\n<<<판매조회 (코드별-{})>>>'.format(subjects[subject]))
            sql = f"""select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, 
                        S.Qty * (select {subject}(unitPrice) from product_history where pCode = '{in_Code}')
                        from sales S, product P where S.sCode = P.pCode and S.sCode = '{in_Code}'"""
                # inner join으로 제품명으로 가져오고, select문에서 서브쿼리로
                # history 테이블에서 최소단가를 가져와 곱한다.
            rows = cd1.db_find_all(sql, "판매코드 개별 조회 오류입니다.")
 
            if rows: 
                st1.print_sales_pname(rows)
                
                print('-'*82)
                amttotal = 0.00
                for row in rows:
                    amttotal = amttotal + row[5]
                print("{}".format(fmt("판매금액합계"66)), end='')
                print(fmt("{:,.2f}".format(amttotal), 14'r'))
 
            else : 
                print("입력하신 코드에 해당하는 판매가 없습니다.")
 
 
 
        del cd1 # 클래스 소멸
 
 
class InputFilter:
    # 사용자 입력값 필터링 클래스
    # 기존에는 전역변수에 입력값을 저장하고, 유효성을 판별한 후 True/False를 반환했다.
    # 22-09-07 : 입력값이 적합하지 않으면 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 : # float형으로 변환했을 때 오류가 발생하면 drate는 None.
            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# 22-09-05 : 선착순 사은품 같은 경우 0개로 입력할 수도 있어 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')
        #    
        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
 
    ### <요구사항-1> 반영 ###
    # 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 : db connect와 close를 반복하지 않고, 
    # connect 객체를 한 번만 생성하기 위해 생성자를 활용했었다.
    # ConnectDB 클래스 작성 후 필요없게 되어 공통적인 코드를 작성한 insert() 메서드를 삭제했다.
 
    def insert_product(self, in_pCode='', rows=None):
    # 22-09-07 : Find 클래스 대신 ConnectDB 활용한 코드로 변경
        if1 = InputFilter()
        ui1 = UserInput()
        cd1 = ConnectDB() # ConnectDB 객체 생성과 동시에 DB connect 객체 생성됨
 
        print("\n<<<제품 등록입니다>>>")
        if in_pCode == '':
            in_pCode = input("등록할 제품코드를 입력하세요 : ")
            rows = if1.set_code(in_pCode, cd1) # 제품코드 유효성 확인 함수 실행
            # set_code 함수가 실행되며 쿼리가 1회 반영된다.
 
        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, "제품 수정에 실패했습니다."
            # insert 하면서 쿼리가 해당 함수 내에서 총 2회 반영된다.
            record_product_history(in_pCode, 'insert', iValue)
            print("\n제품 등록을 성공했습니다.")
            print()
 
        del cd1 # 소멸자 : 쿼리 2회 반영 후 DB 관련 객체가 close 된다.
 
    def insert_sales(self, in_sCode='', rows=None):
        # 22-09-07 : Find 클래스 대신 ConnectDB 활용한 코드로 변경
        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값을 가져와서 Amt값을 삽입한다.
            cd1.db_commit(sql, "판매 등록에 실패했습니다.")
            print("\n판매 등록을 성공했습니다.")
            print()        
 
        del cd1 # ConnectDB 소멸
        
class Update:
    # 테이블에 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에 쿼리 반영
                record_product_history(in_pCode, 'update', iValue)
                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> 반영###
            # 22-09-08 : ls_seqNo.append(str(rows))하는 대신 map 함수를 활용하여 형변환한다.
            ls_seqNo = list(map(str, ls_seqNo)) # 입력받은 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:
    # 테이블에 delete를 수행하는 메서드의 모음.
    # update 테이블과 거의 유사한 구조이지만, 코드 가독성 향상과
    # 기능별 분리를 위해 별도의 클래스로 분리함.
    # 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('삭제 성공했습니다.')
                record_product_history(in_pCode, 'delete')
 
                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:
# 테이블을 초기화하는 reset메서드가 있는 클래스
# 22-09-28 : reset_product와 reset_sales 메서드 분리. history 처리 위함.
 
    def reset_product(self):
        st1 = ShowTables() 
        cd1 = ConnectDB()
 
        sql = f"select * from product"
        find_rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.")
        
        if find_rows : 
            st1.print_product(find_rows) 
 
            print(f'\n<<<제품테이블 초기화입니다>>>')
            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 별도 초기화 필요 없어짐
                sql1 = f"truncate table product"
                cd1.db_commit(sql1, "초기화에 실패했습니다.")
 
                # 22-09-28 : 초기화 후 기본 데이터 insert
                sql1 = """insert into product(pCode,pName,unitPrice) values
                        ('a001','마우스', 100),
                        ('a002','키보드', 200),
                        ('a003','무선마우스', 300),
                        ('a004','무선키보드', 400),
                        ('a005','24형모니터', 500),
                        ('a006','27형모니터', 600),
                        ('a007','32형모니터', 700),
                        ('a008','500GB-ssd', 800),
                        ('a009','1TB-ssd', 900),
                        ('a010','2TB-ssd', 1000);"""
                cd1.db_commit(sql1)
                
                # 히스토리 테이블도 초기화
                sql2 = "truncate table product_history"
                cd1.db_commit(sql2)
                sql2 = "select * from product"
                rows = cd1.db_find_all(sql2)
                record_product_history(None'reset', rows)
 
                print("초기화 성공했습니다.")
            else : 
                print("<<<초기화를 취소했습니다.>>>")
        else : 
            print("삭제할 데이터가 없습니다.")
            print("<<<초기화를 취소합니다.>>>")
        
        del cd1
 
    def reset_sales(self):
        st1 = ShowTables() 
        cd1 = ConnectDB()
 
        sql = f"select * from sales"
        find_rows = cd1.db_find_all(sql, "전체 목록 조회에 실패했습니다.")
        
        if find_rows : 
            st1.print_sales(find_rows)        
 
            print(f'\n<<<판매테이블 초기화입니다>>>')
            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 sales"
                cd1.db_commit(sql, "초기화에 실패했습니다.")
                # 22-09-28 : 초기화 후 기본 데이터 insert
                sql = """insert into sales(sCode,sDate,qty,amt) values 
                        ('a001','2022-09-22 09:24:58',1, 100),
                        ('a002','2022-09-22 09:24:58',2, 400),
                        ('a001','2022-09-22 09:24:58',3, 300),
                        ('a003','2022-09-22 09:24:58',1, 300),
                        ('a003','2022-09-22 09:24:58',2, 600),
                        ('a003','2022-09-22 09:24:58',3, 900),
                        ('a003','2022-09-22 09:24:58',4, 1200),
                        ('a004','2022-09-22 09:24:58',1, 400),
                        ('a004','2022-09-22 09:24:58',2, 800),
                        ('a004','2022-09-22 09:24:58',3, 1200),
                        ('a004','2022-09-22 09:24:58',4, 1600),
                        ('a005','2022-09-22 09:24:58',1, 500),
                        ('a005','2022-09-22 09:24:58',2, 1000),
                        ('a005','2022-09-22 09:24:58',3, 1500),
                        ('a005','2022-09-22 09:24:58',4, 2000),
                        ('a006','2022-09-22 09:24:58',1, 600),
                        ('a006','2022-09-22 09:24:58',2, 1200),
                        ('a006','2022-09-22 09:24:58',3, 1800),
                        ('a006','2022-09-22 09:24:58',4, 2400),
                        ('a007','2022-09-22 09:24:58',1, 700),
                        ('a007','2022-09-22 09:24:58',2, 1400),
                        ('a007','2022-09-22 09:24:58',3, 2100),
                        ('a007','2022-09-22 09:24:58',4, 2800),
                        ('a008','2022-09-22 09:24:58',1, 800),
                        ('a008','2022-09-22 09:24:58',2, 1600),
                        ('a008','2022-09-22 09:24:58',3, 2400),
                        ('a008','2022-09-22 09:24:58',4, 3200),
                        ('a009','2022-09-22 09:24:58',1, 900),
                        ('a009','2022-09-22 09:24:58',2, 1800),
                        ('a009','2022-09-22 09:24:58',3, 2700),
                        ('a009','2022-09-22 09:24:58',4, 3600),
                        ('a010','2022-09-22 09:24:58',1, 1000),
                        ('a010','2022-09-22 09:24:58',2, 2000),
                        ('a010','2022-09-22 09:24:58',3, 3000),
                        ('a010','2022-09-22 09:24:58',4, 4000);"""
                cd1.db_commit(sql)
 
                print("초기화 성공했습니다.")
            else : 
                print("<<<초기화를 취소했습니다.>>>")
        else : 
            print("삭제할 데이터가 없습니다.")
            print("<<<초기화를 취소합니다.>>>")
        
        del cd1
 
if __name__ == "__main__" :
    create_table() # 테이블이 없을 경우 생성하는 메서드
    while True:
        os.system('cls'# 화면을 보기 좋게 비운다.
 
        # 22-09-29 세무자료 섹션 추가
        print("-----제품관리-----    |    -----판매관리-----    |    --판매조회(코드별)--")
        print("제품     등록 : 01    |    판매     등록 : 11    |    세 무 자 료 용 : 21")
        print("제품목록 조회 : 02    |    판매목록 조회 : 12    |    주 주 총 회 용 : 22")
        print("코드별   조회 : 03    |    코드별   조회 : 13    |    ")
        print("제품명별 조회 : 04    |    제품명별 조회 : 14    |    ")
        print("제품     수정 : 05    |    판매     수정 : 15    |    ")
        print("제품     삭제 : 06    |    판매     삭제 : 16    |    ")
        print("테이블 초기화 : 07    |    테이블 초기화 : 17    |    ")
        print("                      |    외부파일 등록 : 18    |    ")
        print("                      |    시각화   출력 : 19    |    ")
        print('----------------------------------------------')
        print("관리     종료 : 00 ")
        print('----------------------------------------------')
        print()
        # 제품관리 아래에 판매관리가 위치하도록 세로로 길게 작성된 형태였다.
        # 22-09-05 : 메뉴 보기가 좋지 않아 테이블 형태로 변경했다.
 
        sel = input("작업을 선택하세요 : ")
        print()
        
        # 1. 메뉴는 앞글자가 0이면 제품 테이블 관련, 1이면 판매 테이블 관련 기능이다.
        # 2. 이 점을 이용하여 if문을 짧게 단축할 수도 있지만,
        #    메뉴 번호별로 구분되어 있는 편이 유지보수에 유리할 것 같아 별도로 작성했다.
        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()
            p7.reset_product()
            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()
            s7.reset_sales()
            os.system("pause")
        elif sel == '18' :
            s8 = FileInsert('s')
            s8.file_insert()
            os.system("pause")
        elif sel == '19' :
            s9 = ShowGraphs('s')
            s9.show_amt_graph()
            os.system("pause")
        #
        elif sel == '21' :
            s10 = Read('s')
            s10.read_code_sales('min')
            os.system("pause")
        #
        elif sel == '22' :
            s10 = Read('s')
            s10.read_code_sales('max')
            os.system("pause")
        #
        elif sel == '00' :
            print("직원관리를 종료합니다. ")
            os.system("pause")
            os.system('cls')
            sys.exit(0)
        else :
            print("잘못 선택했습니다. ")
            os.system("pause")    
 
cs

 

DBContoller.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
import pymysql # MySQL데이터베이스를 사용하기 위한 라이브러리를 등록함
import datetime
 
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    # 한글을 사용하겠다는 설정 
    }
 
def record_product_history(pCode, work_name, value=None):
# 22-09-27 추가 : product_history테이블에 기록하는 메서드
    cd1 = ConnectDB()
    now = datetime.datetime.now()
 
    if work_name == 'reset' : # 초기화 했을 경우 기본 데이터 레코드를 삽입
        sql = f"insert into product_history(pCode, pName, unitPrice, discountRate, validFrom) values(%s, %s, %s, %s, '{now}')"
        cd1.db_commint_many(sql, value)
    else : # reset이 아닌 다른 작업을 할 경우
        sql = "update product_history set validUntil = " + f"'{now}'"+" where pCode="+f"'{pCode}'" + "and validUntil='9999-12-31 23:59:59'"
        cd1.db_commit(sql) # 직전 레코드의 기한을 변경함
        if work_name != 'delete' : # insert, update 작업일 경우 레코드 추가
            sql = f"insert into product_history(pCode, pName, unitPrice, discountRate, validFrom) values('{pCode}', '{value[0]}', '{value[1]}', '{value[2]}', '{now}')"
            cd1.db_commit(sql)
 
class ConnectDB: 
# 22-09-06 : DBController 파일로 분리 후 클래스로 변경하여 재작성    
# 1. Read 클래스와 의미상 중복되는 Find클래스를 없애고 ConnectDB로 교체했다.
# 2. 처음 버전은 함수로 작성하였는데, 함수를 호출할 때마다(sql문을 실행할 때마다) connect와 close가 반복되었다.
# 3. 2의 문제점을 개선하여 매개변수를 딕셔너리로 변경했다. 
#    {sql문:'commit', sql문:'fetchall'}형태로 인수를 받으려고 했다.
# 4. 하지만 딕셔너리에 있는 쿼리문을 for문을 활용하여 한번에 실행하면, 
#    여러 쿼리를 실행하는 중간에 다른 코드를 삽입하지 못한다. 
# 5. 한번에 쿼리를 실행하기 때문에 어느 기능과 부분에서 어떤 쿼리가 실행되는지 알기도 힘들었다.
# 6. 그래서, 클래스의 생성자와 소멸자를 try~finally 형식으로 사용하기로 했다.
# 7. 생성자가 try, 소멸자가 finally라고 생각하면 된다.
    conn, cursor = NoneNone
    
    def __init__(self) :
    # 실행하고자 하는 기능(메뉴)에서 클래스를 생성하면 DB 연결 객체가 생성된다.    
        try:
            self.conn = pymysql.connect(**config)
            # 딕셔너리 config를 인수로 사용하여 conn 객체 생성
            self.cursor = self.conn.cursor()  
            # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수 생성
        except Exception :
            print("데이터베이스 연동 실패")
 
    def db_commit(self, sql, error_msg=''): 
    # insert, update, delete 등 commit이 필요한 쿼리를 실행하는 메서드    
        try:
            self.cursor.execute(sql) # sql 반영
            self.conn.commit() # 커밋
        except Exception as e:
            if error_msg == ''
                error_msg = "db연동실패 : "+ str(e)
            print(error_msg)
            self.conn.rollback() 
    
    def db_commint_many(self, sql, rows, error_msg=''):
    # 22-09-28 : 여러개의 쿼리를 commit하는 메서드 추가
        try:
            self.cursor.executemany(sql, rows) # 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=''):
    # select 쿼리를 실행하여 결과를 전부 가져오는 메서드    
        try:
            self.cursor.execute(sql) # 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=''):
    # select 쿼리를 실행하여 결과를 첫줄만 가져오는 메서드  
        try:
            self.cursor.execute(sql) # 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):
    # 기능(메뉴)에서 실행하고자 하는 모든 쿼리문을 실행했다면,
    # 객체를 del(소멸)시킴으로써 생성되었던 객체를 close 한다.
    # 이를 통해 db 객체 생성과 close를 무한 반복하지 않고 원하는 곳에서 close를 수행할 수 있다.
        self.cursor.close() # cursor 객체 close
        self.conn.close() # conn 객체 close
 
 
cs

 

 

 

 

댓글