[PYTHON] 3. MySQL Query

Fly High!·2020년 8월 30일
0

Python

목록 보기
3/7
post-thumbnail

RDBMS (Relational Database Management System)

  • 역사가 오래되어, 신뢰성이 높고, 빠름
  • 관계형 데이터베이스 = Table
  • Structured by Attribute & Attribute value

    Primary key
    : 각 Row(행)를 유일하게 식별해주는 Column(열)
    : 테이블마다 존재하고 NULL 값 허용 X

SQL (Structured Query Language)

  • RDBMS를 관리하기 위한 표준 프로그래밍 언어

pymysql module 사용하기

INSERT

try:
  sql = 'INSERT INTO table (columns) VALUES (%s)'
  # table = DB내의 Table명
  # columns = 넣고자 하는 columns 지정 (생략 가능)
  # %s = column 값

  cursor.execute(sql, data)
  # data = 넣고 싶은 값, %s의 개수와 맞아야함

  db.commit()
 
 finally:
  db.close()

UPDATE

try:
  sql = 'UPDATE table SET column = %s WHERE column = %s or primary key = %s'
  # SET = update 값 지정
  # WHERE = update 할 값 지정
  
  cursor.execute(sql, data)
  db.commit()

finally:
  db.close()

DELETE

try:
  sql = 'DELETE FROM table WHERE column = %s or primary key = %s'
  # WHERE = delete 할 값 지정
  
  cursor.execute(sql, data)
  db.commit()

finally:
  db.close()

SELECT

try:
  sql = 'SELECT * FROM table WHERE column = %s or primary key = %s'
  cursor.execute(sql, data)
  result = cursor.fetchall() or fetchone() or fetchmany(n)
  # fetchall()   = 모든 데이터를 client로 가져올 때 사용
  # fetchone()   = 한번에 하나의 row만을 가져올 때 사용
  # fetchmany(n) = n개 만큼의 데이터를 가져올 때 사용

finally:
  db.close()

DictCursor

cursor = db.curosr(pymysql.cursors.DictCursor)
  • value를 tuple이 아닌 dictionary형태로 리턴
  • column수가 많거나 pandas에 사용할 때 유용함

try문의 사용
: close를 하지 않고 열린 상태를 유지하면 connection leak이 생기는데 이를 방지하기 위해 잊지 말고 사용

profile
Back-end, Python, Data

0개의 댓글