파이썬과 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 연결 닫기 성공")