4. PyMySQL 익혀보기 > 4-4. PyMySQL 기본 문법_SELECT

PyMySQL 기본 문법_SELECT

SELECT역시 INSERT와 마찬가지로 Workbench에서 진행해준 방법과 크게 다르지 않습니다. 연습했던 쿼리들을 PyMySQL에서도 적용해보세요.

기본 SELECT

import pymysql

host_name = 'localhost'
host_port = 3306 
username = 'root'
password = ''
database_name = 'test'

db = pymysql.connect(
     host=host_name,     # MySQL Server Address
     port=host_port,     # MySQL Server Port
     user=username,      # MySQL username
     passwd=password,    # password for MySQL username
     db=database_name,   # Database name
     charset='utf8'
 )

sql="""
SELECT * FROM COSADAMA;
"""

cursor.execute(sql)
    
db.commit()
db.close()

SELECT + for

이번에는 SELECT구문을 통해 DB에서 가져온 데이터를 배열(array) 형식으로 저장(fetch)하여 사용해봅시다. DB에 저장된 데이터의 경우 그 크기가 엄청날 수 있습니다. 이런 빅데이터를 빠르게 연산하기 위해서 배열(array) 형식으로 바꾸어 처리하곤 하며 이때 사용하는 것이 fetch이죠. fetch는 사용하는 상황에 따라서 아래 함수 중에서 선택하여 사용하면 됩니다.

  • fetch: 나열, 정렬하다.
  • fetchone(): 한 행row만 가져옵니다.
  • fetchmany(size= ): size만큼의 row를 가져옵니다.
  • fetchall(): 모든 row를 가져옵니다.

아래 예시 코드들을 보며 fetch의 사용을 이해해보세요.

import pymysql

host_name = 'localhost'
host_port = 3306 
username = 'root'
password = ''
database_name = 'test'

db = pymysql.connect(
     host=host_name,     # MySQL Server Address
     port=host_port,     # MySQL Server Port
     user=username,      # MySQL username
     passwd=password,    # password for MySQL username
     db=database_name,   # Database name
     charset='utf8'
 )
 
try:
    cursor = db.cursor()
    sql = "SELECT * FROM COSADAMA"

    cursor.execute(sql)
    result = cursor.fetchall()

       for i in range(4):
           for row_data in result:
                   print(row_data[i])
       
       print(result.info())

fianlly:
    db.close()
import pymysql

host_name = 'localhost'
host_port = 3306
username = 'root'
password = ''
database_name = 'test'

db = pymysql.connect(
     host=host_name,     # MySQL Server Address
     port=host_port,     # MySQL Server Port
     user=username,      # MySQL username
     passwd=password,    # password for MySQL username
     db=database_name,   # Database name
     charset='utf8'
 )

try:
    cursor = db.cursor()
    sql = "SELECT * FROM COSADAMA"
    
    cursor.execute(sql)
    result = cursor.fetchall()
    
    for row_data in result:
        print(row_data[0])
        print(row_data[1])
        print(row_data[2])
        #print(row_data[3])

finally:
    db.close()
host_name = 'localhost'
host_port = 3306
username = 'root'
password = ''
database_name = 'test'

db = pymysql.connect(
     host=host_name,     # MySQL Server Address
     port=host_port,     # MySQL Server Port
     user=username,      # MySQL username
     passwd=password,    # password for MySQL username
     db=database_name,   # Database name
     charset='utf8'
 )

try:
    with db.cursor as cursor:
        sql = "SELECT * FROM COSADAMA WHERE name ='고다람'"

        cursor.execute(sql)

        while result:
            result = cursor.fetchone()
            print(result)

finally:
    db.close()
마지막으로 업데이트 된 날짜:
2022년 9월 24일