본문 바로가기

SeSAC 금융데이터 분석가/SQL

9/8 목

728x90

1. pymysql

import pymysql

class Py2DB:
    pass
# 여기도 실행은 되지만 사용은 지양. 클래스 호출 시 출력되는 것을 원하지 않는다면 주석처리 혹은 삭제
# print('Hello! 1')

# 이 파일을 실행할 경우 실행할 코드py
if __name__ == '__main__':
    print('DB 테스트')
    
    # DB config 파일 읽어보기
    db_config = {}
    with open('./db_config', 'r') as f:
        for l in f.readlines():
            key, value = l.rstrip().split('=')
            if key == 'port':
                db_config[key] = int(value)
            else:
                db_config[key] = value
        # print(db_config)

    print('DB 연결 시작!')
    try:
        conn = pymysql.connect(**db_config)
        
        print('DB 접속 성공')
        
        # 데이터 입력 한 개만 INSERT
        # try:
            # with conn.cursor() as cursor:
            #     sql = '''INSERT INTO `Students`(`name`, `email`, `phone`, `major`)
            #     VALUES(%s, %s, %s, %s)'''
            #     cursor.execute(sql, ('홍길동', '1234@naver.com',
            #                         '010xxxxxxxx', '산업공학과'))
            #     conn.commit()
        # except:
            # print('데이터 삽입 실패')

        # 데이터 Dictionary로 INSERT
        # try:
        #     with conn.cursor() as cursor:
        #         sql = '''INSERT INTO `Students`({})
        #         VALUES({})
        #         '''

        #         v_dict = {
        #         'name': '나나', 
        #         'email': 'nana@naver.com', 
        #         'phone': '010xxxxxxxx', 
        #         'major': '건축공학과'
        #         }

        #         sql = sql.format(','.join(v_dict.keys()), ','.join(['%s'] * len(v_dict)))
        #         cursor.execute(sql, tuple(v_dict.values()))
        #         conn.commit()

        # except Exception as e:
        #     print(e, 'dictionary로 데이터 삽입 실패')

        # 데이터 입력 여러 개 INSERT
        # try:
        #     with conn.cursor() as cursor:
        #         sql = '''INSERT INTO `Students`(`name`, `email`, `phone`, `major`)
        #         VALUES(%s, %s, %s, %s)'''
        #         cursor.executemany(sql, [
        #             ('성춘향', 'aa@aa.aa', '010xxxxxxxx', '전자공학과'),
        #             ('사또', 'bb@bb.bb', '010xxxxxxxx', '교육학과')
        #             ])
        #         conn.commit()

        # except:
        #     print('데이터 다량 삽입 실패')
        
        # UPDATE
        # try:
        #     with conn.cursor() as cursor:
        #         sql = '''UPDATE `Students` SET `email`=%s WHERE `id`=%s
        #         '''
        #         cursor.execute(sql, ('python@python.org', 1,))
        #         conn.commit()

        # except:
        #     print('업데이트 실패')

        # DELETE
        # try:
        #     with conn.cursor() as cursor:
        #         sql = '''DELETE FROM `Students` WHERE `id`=%s
        #         '''
        #         cursor.execute(sql, (1, ))
        #         conn.commit()

        # except:
        #     print('삭제 실패')

        # DELETE MANY
        # try:
        #     with conn.cursor() as cursor:
        #         sql = '''DELETE FROM `Students` WHERE `id` IN (%s, %s)
        #         '''
        #         cursor.execute(sql, (2, 3, ))
        #         conn.commit()
                
        # except:
        #     print('다량 삭제 실패')

        # SELECT
        try:
            with conn.cursor() as cursor:
                sql = '''SELECT * FROM `Students`
                '''
                cursor.execute(sql, )
                result = cursor.fetchall()
                # result = cursor.fetchone()
            print(result)
            # print('타입', type(result))
            # print('길이', len(result))

        except Exception as e:
            print(e) # 에러 메시지 확인
            '''
            (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ',,,,,' at line 1")
            '''
            print('셀렉트 실패')

        print('DB 연결 해제')
        conn.close()
        
    except:
        print('DB 접속 실패')

cf. pymysql로 작성할 때 테이블, 칼럼명 입력시 ` (backtick - 느낌표 좌측 키) 사용

cf. try, except 사용 시 Exception as e로 어떤 에러가 발생했는지 메시지를 볼 수 있음

cf. 숨겨야 할 정보가 있다면 .env(django), .secret, config 파일로 따로 빼주고, with open, readlines()로 가져오자

 

2. MariaDB

유저 및 권한 조회

--유저 및 권한 조회
SELECT GRANTEE, PRIVILEGE_TYPE, IS_GRANTABLE FROM INFORMATION_SCHEMA.USER_PRIVILEGES;

--프라이빗 IPv4 주소에 권한 주기
GRANT ALL PRIVILEGES ON study.* TO jiyeon@172.31.44.249;

--유저에게 할당된 권한 확인
SHOW GRANTS FOR jiyeon@172.31.44.249;

--이미 만들어진 테이블에 FK 추가할 때
ALTER TABLE Grades ADD CONSTRAINT 'FK_Grades_Students';

--제약조건 확인. 기존에 만들었던 id 초기화 하려면 조건 먼저 확인하고 지워야
SELECT * FROM information_schema.table_constraints;

--해당하는 제약조건 삭제
ALTER TABLE Grades DROP CONSTRAINT `Grades_ibfk_1`;

--테이블 초기화
TRUNCATE TABLE Students;

--제약조건(FK) 다시 부여
ALTER TABLE Grades ADD CONSTRAINT 'FK_Grades_Students' 
	FOREIGN KEY(student_id) REFERENCES Students(id);
    
--다중 INNER JOIN
SELECT *
FROM Products
INNER JOIN Suppliers, Categories
ON Products.SuppliersID = Suppliers.SupplierID
AND Products.CategoryID = Categories.CategoryID;

 

728x90