AI 그게 뭔데
끄적끄적 개발일지
AI 그게 뭔데
전체 방문자
오늘
어제
  • 분류 전체보기 (342)
    • 논문 (5)
    • DL(Deep-Learning) (34)
      • 개념 (14)
      • Python 기초 (14)
      • Tensorflow (6)
      • Pytorch (0)
    • NLP (10)
    • OpenCV (53)
    • DevOps (10)
      • AWS (2)
      • Docker & Kubernetes (4)
      • Spark (3)
      • SQL (1)
    • MacOS (1)
    • React-Native (2)
    • BI (3)
      • GA(Google Analytics) (3)
      • Tableau (0)
    • 알고리즘 (221)
      • 백준 (76)
      • 프로그래머스 (108)
      • 기타 알고리즘 (37)

인기 글

태그

  • 백준
  • 파이썬
  • 알고리즘
  • OpenCV
  • level1
  • 연습문제
  • LEVEL2
  • 프로그래머스
  • 이코테
  • Python

최근 글

hELLO · Designed By 정상우.
AI 그게 뭔데

끄적끄적 개발일지

DevOps/SQL

MySQL과 PYTHON 연동하기

2022. 1. 24. 22:37

파이썬과 MySQL을 연결해보자

 

PyMySQL 패키지 설치

pip install PyMySQL

 

 

DB 연결 - connect()

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mysql',
                         charset = 'utf8')
    print("DB 연결 성공")

except Exception as e:
    print(e) # DB 연결 실패 시 오류 내용 출력
    
finally:
    if db is not None : # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")

 

connect() 함수를 이용하면 MySQL host내 DB와 직접 연결할 수 있다.

  • user : user name
  • passwd : 설정한 패스워드
  • host : DB가 존재하는 host
  • db : 연결할 데이터베이스 이름
  • charset : 인코딩 설정

모두 텍스트로 인자를 넘겨야 한다.

 

 

Table 생성

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mydb',
                         charset='utf8')
    print("DB 연결 성공")

    sql = '''
    create table tb_student(
    id int primary key auto_increment not null,
    name varchar(32),
    age int,
    address varchar(32)
    ) engine = InnoDB default charset=utf8
    '''

    with db.cursor() as cursor:
        cursor.execute(sql)

except Exception as e:
    print(e)  # DB 연결 실패 시 오류 내용 출력

finally:
    if db is not None:  # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")

 

 

데이터 삽입

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mydb',
                         charset = 'utf8')
    print("DB 연결 성공")

    sql ='''
    insert tb_student(name, age, address) values('yul', 26, 'Korea')
    '''
    
    with db.cursor() as cursor:
        cursor.execute(sql)
    db.commit()
    
    

except Exception as e:
    print(e) # DB 연결 실패 시 오류 내용 출력
    
finally:
    if db is not None : # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")

 

 

데이터 변경

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mydb',
                         charset='utf8')
    print("DB 연결 성공")

    id = 2
    sql = '''
    update tb_student set name='YURI',age=25 where id = %d
    ''' % id

    with db.cursor() as cursor:
        cursor.execute(sql)
    db.commit()

except Exception as e:
    print(e)  # DB 연결 실패 시 오류 내용 출력

finally:
    if db is not None:  # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")

 

 

데이터 삭제

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mydb',
                         charset='utf8')
    print("DB 연결 성공")

    id = 1
    sql = '''
    DELETE FROM tb_student WHERE id=%d
    ''' % id

    with db.cursor() as cursor:
        cursor.execute(sql)
    db.commit()

except Exception as e:
    print(e)  # DB 연결 실패 시 오류 내용 출력

finally:
    if db is not None:  # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")

 

 

다수의 데이터 삽입

import pymysql

db = None

try:
    db = pymysql.connect(host='localhost',
                         user='root',
                         passwd='####',
                         db='mydb',
                         charset='utf8')
    print("DB 연결 성공")

    students = [
        {
            'name': 'RIMS',
            'age': 31,
            'address': 'SEOUL'
        },
        {
            'name': 'SUZY',
            'age': 28,
            'address': 'PUSAN'
        },
    ]

    for s in students:
        with db.cursor() as cursor:
            sql = '''
            insert tb_student(name, age, address) values(%s,%d,%s)
            ''' % (s['name'], s['age'], s['address'])
            cursor.execute(sql)

    db.commit()

    # 30대 학생만 조회 ②
    cond_age = 30
    with db.cursor(pymysql.cursors.DictCursor) as cursor:
        sql = '''
        select from tb_student where age > %d
        ''' % cond_age
        cursor.execute(sql)
        results = cursor.fetchall()
    print(results)  #가져온 데이터 출력

    cond_name = 'AIRIM'  # 찾고자 하는 이름
    with db.cursor(pymysql.cursors.DictCursor) as cursor:
        sql = '''
        select from tb_student where name="%s"
        ''' % cond_name
        cursor.execute(sql)
        result = cursor.fetchone()  #select 구문으로 조회한 데이터 중 하나만 불러오는 함수
    print(result[' name'], result['age'])
    #pandas 데이터 프레임으로 표현

    df = pd.DataFrame(results)
    print(df)

except Exception as e:
    print(e)  # DB 연결 실패 시 오류 내용 출력

finally:
    if db is not None:  # DB 가 연결된 경우에만 접속 닫기 시도
        db.close()
        print("DB 연결 닫기 성공")
    AI 그게 뭔데
    AI 그게 뭔데
    공부와 개발 그리고 AI가 약간 첨가된 흔적 남기기

    티스토리툴바