본문으로 바로가기

python db 수동 연결 샘플 pymysql

category Python 2019. 10. 21. 15:32
    try:
        # MySQL Connection 연결
        conn = pymysql.connect(host='DB주소', user='계정', password='패스워드',db='DB이름', charset='utf8', cursorclass=pymysql.cursors.DictCursor)

        # Connection 으로부터 Cursor 생성
        curs = conn.cursor()

        try:
            # SQL문 실행
            sql = "실행 할 쿼리"

            curs.execute(sql)

            # 데이타 Fetch
            rows = curs.fetchall()
            # print(rows)  # 전체 rows

            for row in rows:
                # print(row[0])
                print(row["컬럼명"]) #cursorclass=pymysql.cursors.DictCursor 옵션 사용

            # 데이터 변화 적용
            # CREATE 혹은 DROP, DELETE, UPDATE, INSERT와 같이 Database 내부의 데이터에 영향을 주는 함수의 경우 commit()을 해주어야 함.
            # conn.commit()

        except Exception:
            print("Error in MySQL query")
        finally:
            # Connection 닫기
            conn.close()

    except Exception:
        print("Error in MySQL connexion")

 

계정정보 외부 파일 사용 하기

 

/common.db.cnf

 

[client] => django에서 기본으로 사용하는 DB
database = db명
host = localhost
user = root
password = 1234

[client_gw]
database = db명
host = DB주소
user = root
password = 1234

 

 

views.py

import requests, datetime, json, os, pymysql, configparser

reader = configparser.RawConfigParser()
    reader.read(os.path.join(settings.BASE_DIR, "common/db.cnf"))
    gw_host = reader.get('client_gw', 'host')
    gw_user = reader.get('client_gw', 'user')
    gw_pw = reader.get('client_gw', 'password')
    gw_db = reader.get('client_gw', 'database')


    try:
        # MySQL Connection 연결
        conn = pymysql.connect(host=gw_host, user=gw_user, password=gw_pw, db=gw_db, charset='utf8', cursorclass=pymysql.cursors.DictCursor)

        # Connection 으로부터 Cursor 생성
        curs = conn.cursor()

        try:
        
            sql = "SQL문"

            curs.execute(sql)

            # 데이타 Fetch
            rows = curs.fetchall()
            # print(rows)  # 전체 rows

            for row in rows:
                team = row["컬럼1"]
                name = row['컬럼2']
                indate = row['날짜1']
                ....

                if indate == '0000-00-00':
                    indate = None

                try:
                    memData = Member.objects.get(msabun=sabun)

                    state_gw = "in"
                    if outdate :

                        if date_validate(outdate):
                            # 퇴사일 date형으로 변환
                            out_date = datetime.datetime.strptime(outdate, '%Y-%m-%d').date()
                            today = datetime.date.today()

                            # 퇴사 체크
                            if out_date < today:
                                print('퇴사한 사원')
                                state_gw = "out"

                                # 그룹웨어에서 퇴사처리
                        else:
                            print('퇴사한 사원인것 같은데 날짜 형식이 맞지 않음 (일단 홀드)')
                    else:
                        print('근무중인 사원')


                    #직급, 입사일, 퇴사일, 그룹웨어상태 수정 // 소속 팀을 수정해야 할지가 애매함
                    if memData.mposition != position or memData.min_date != indate or memData.mout_date != outdate or memData.mstate_gw != state_gw :
                        memData.mposition = position
                        memData.min_date = indate
                        memData.mout_date = outdate
                        memData.mstate_gw = state_gw
                        memData.save()

                    print('{0}({1})사원정보 수정'.format(name, sabun))

                except Member.DoesNotExist:

                    state_gw = "in"
                    if outdate:

                        if date_validate(outdate):
                            # 퇴사일 date형으로 변환
                            out_date = datetime.datetime.strptime(outdate, '%Y-%m-%d').date()
                            today = datetime.date.today()

                            # 퇴사 체크
                            if out_date < today:
                                print('퇴사한 사원')
                                state_gw = "out"

                                # 그룹웨어에서 퇴사처리
                        else:
                            print('퇴사한 사원인것 같은데 날짜 형식이 맞지 않음 (일단 홀드)')
                    else:
                        print('근무중인 사원')


                    obj = Member(
                        msabun=sabun,
                        mname=name,
                        mposition=position,
                        mteam=team,
                        min_date=indate,
                        mout_date=outdate,
                        mroot='gw',
                        mstate_gw=state_gw
                    )
                    obj.save()

                    print('{0}({1})사원정보 신규등록'.format(name, sabun))

        except Exception:
            print("Error in MySQL query")
        finally:
            # Connection 닫기
            conn.close()

    except Exception:
        print("Error in MySQL connexion")
        
        
        

 

 

 

참조 

https://sab-jil.tistory.com/6

http://zetcode.com/python/pymysql/