Python with MySQL

hh_binvely·2024년 3월 11일
0

Part 03. SQL

목록 보기
7/11
post-thumbnail

1. 연동을 위한 Python 모듈 설치하기

  • 나는 pymysql을 설치함.
  • pip이나 whl파일을 이용하여 설치 가능

2. MySQL에 연결하기

import pymysql
db = pymysql.connect(
    port    =	,	# write on by int
    user    = '',	#root, id, ...
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',	#생략도 가능
    charset = 'utf8'
)
db.close()	#연결 종료

3. table 생성하기

import pymysql
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8'
)
cursor = db.cursor()
sql = '''
create table sql_file
(
 id int,
 filename varchar(16)
)
'''
cursor.execute(sql)
db.close()

cursor()란?

  • cursor: 하나의 DB connection에 대하여 독립적으로 SQL 문을 실행할 수 있는 작업환경을 제공하는 객체
  • 하나의 connection에 동시에 한개의 cursor만 생성가능
  • cursor를 통해서 SQL 문을 실행할 수 있으며, 응용 프로그램이 실행결과를 튜플(tuple) 단위로 접근할 수 있도록함.

4. table 삭제하기

import pymysql
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8'
)
cursor = db.cursor()
sql = '''
drop table sql_file
'''
cursor.execute(sql)
db.close()

5. SQL File 실행하기

  • 쿼리 파일에 쿼리가 1개인 경우
import pymysql
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8'
)
cursor = db.cursor()
sql = open('<SQL File Name>.sql').read()
cursor.execute(sql)
db.close()
  • 쿼리 파일에 쿼리가 여러 개인 경우
    - pymysql의 경우, 강의와 옵션이 상이했다.
import pymysql
from pymysql.constants import CLIENT
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8',
    client_flag=CLIENT.MULTI_STATEMENTS		# 여러 개 쿼리 사용할 수 있도록 해주는 옵션
)
cursor = db.cursor()
sql = open('<SQL File Name>.sql').read()
cursor.execute(sql)
db.commit()	#commit을 실행해야지만 db에 저장됨
db.close()

6. fetchall() 사용

  • 모든 데이터를 한꺼번에 클라이언트로 가져올 때 사용
import pymysql
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8'
)
cursor = db.cursor()
sql = '''
    select * from sql_file
    '''
cursor.execute(sql)
datas = cursor.fetchall()
for d in datas:
    print(d)
db.close()

* 데이터를 pandas로 변환하기

import pymysql
import pandas as pd
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8'
)
cursor = db.cursor()
sql = '''
    select * from sql_file
    '''
cursor.execute(sql)
datas = cursor.fetchall()
df = pd.DataFrame(datas)
print (df)
db.close()

7. Python with CSV

df = pd.read_csv('police_station.csv', encoding='cp949')
#print (df)
from pymysql.constants import CLIENT
db = pymysql.connect(
    port    =	,
    user    = '',
    passwd  = 'pw',
    host    = 'host',
    db      = 'dbName',
    charset = 'utf8',
    client_flag=CLIENT.MULTI_STATEMENTS
)
cursor = db.cursor()
sql = '''
insert into police_station values (%s, %s)
'''
for i, r in df.iterrows():
    cursor.execute(sql, tuple(r))
    db.commit()
# 결과 조회
sql = '''
select * from police_station
'''
cursor.execute(sql)
datas = cursor.fetchall()
df = pd.DataFrame(datas)
print (df)
db.close()

0개의 댓글

관련 채용 정보