[Python] MySQL 사용방법

2023. 8. 21. 11:00카테고리 없음

반응형

□ MySQL데이터베이스 사용방법

MySQL 데이터베이스에 대해 사용방법을 알아봅니다. DB생성, 테이블 생성-삭제, DML문법을 알아봅니다.

 

 

 데이터 베이스 사용을 위한 환경설정.

파이선에서 MySQL데이터베이스를 사용하기 위해선 PyMySQL이란 패키지를 설치해야 합니다.

 

▶︎ 인스톨방법

shell> pip install PyMySQL
[root@singledb ~]# pip install PyMySQL
Collecting PyMySQL
  Downloading PyMySQL-0.10.1-py2.py3-none-any.whl (47 kB)
     |████████████████████████████████| 47 kB 298 kB/s 
Installing collected packages: PyMySQL
Successfully installed PyMySQL-0.10.1
WARNING: You are using pip version 20.3.1; however, version 20.3.3 is available.
You should consider upgrading via the '/usr/bin/python3 -m pip install --upgrade pip' command.

만약 버전업 관련 warning 발생한다면 무시하셔도 되며 상위 버전이 필요하다면 업그레이드 해주시면 됩니다.

 

 데이터 베이스 접속방법

▶︎ 예제코드

# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
    user='root', 
    passwd='{설정한 비밀번호}', 
    host='127.0.0.1', 
    db='juso-db', 
    charset='utf8'
)

 

▶︎ 접속정보

위의 접속정보에 대한 상세 설명입니다.

user : 접속계정

passwd : 접속암호

host : 접속 IP 혹은 도메인

db : 데이터베이스명

charset : 접속 캐릭터셋

 

 

 데이터 베이스 생성

▶︎ 예제코드

코드 : 

# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8') 


# 커서를 선언합니다.
cursor = conn_db.cursor() 

# SQL을 작성합니다.
sql = "CREATE DATABASE sampledb" 

#SQL을 수행합니다.
cursor.execute(sql)

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sampledb           |
| sys                |
+--------------------+
6 rows in set (0.00 sec)

 

 테이블 생성

▶︎ 예제코드

코드 : 
# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8',
db='sampledb'
) 


# 커서를 선언합니다.
cursor = conn_db.cursor() 

# SQL을 작성합니다.
sql = '''CREATE TABLE member ( 
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
email varchar(255), 
dept varchar(255) 
) 
''' 

#SQL을 수행합니다.
cursor.execute(sql)

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
mysql> use sampledb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+--------------------+
| Tables_in_sampledb |
+--------------------+
| member             |
+--------------------+
1 row in set (0.00 sec)

 

 

 

 데이터 입력

▶︎ 예제코드

코드 : 
# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8',
db='sampledb'
) 


# 커서를 선언합니다.
cursor = conn_db.cursor() 

# SQL 템플릿을 만듭니다.
sql = "INSERT INTO member (email, dept) VALUES (%s, %s)" 

# SQL 템플릿을 커서에 맵핑 후 수행합니다.
cursor.execute(sql,("president@hcompany.com", "C1")) 
cursor.execute(sql,("empoyee@hcompany.com", "Q2")) 
cursor.execute(sql,("develop@hcompany.com", "B3")) 

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
mysql> use sampledb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from member; 
+----+------------------------+------+
| id | email                  | dept |
+----+------------------------+------+
|  1 | president@hcompany.com | C1   |
|  2 | empoyee@hcompany.com   | Q2   |
|  3 | develop@hcompany.com   | B3   |
+----+------------------------+------+
3 rows in set (0.00 sec)

 

 

 데이터 조회

▶︎ 예제코드

코드 : 

# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8',
db='sampledb'
) 

# 커서를 선언합니다.
# 커서 매개변수를 공란으로 넘길때는 row 컬럼을 가져올 때 index방식으로 가져옵니다.
# 커서 매개변수를 pymysql.cursors.DictCursor으로 넘길때는 row 컬럼을 가져올 때 키(DB컬럼명) 방식으로 가져옵니다.
cursor = conn_db.cursor()
# cursor = conn_db.cursor(pymysql.cursors.DictCursor)


# SQL 템플릿을 만듭니다.
sql = "SELECT * FROM member where dept = %s" 

# SQL 템플릿을 커서에 맵핑 후 수행합니다.
cursor.execute(sql, ("Q2")) 
rows = cursor.fetchall() 

for row in rows: 
        # 로우 데이터 출력
        print(row)

        # 컬럼 데이터 출력
        # 위의 커서 방식에 따라 인덱스 방식, 키(DB컬럼명) 방식이 결정됩니다.
        print(row[0], row[1], row[2])
        # print(row["id"], row["email"], row["dept"])
        

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
(2, 'empoyee@hcompany.com', 'Q2')

 

 

 데이터 수정

▶︎ 예제코드

코드 : 

# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8',
db='sampledb'
) 


# 커서를 선언합니다.
cursor = conn_db.cursor() 

# SQL 템플릿을 만듭니다.
sql = "UPDATE member SET dept = %s WHERE email = %s"

# SQL 템플릿을 커서에 맵핑 후 수행합니다.
cursor.execute(sql, ("Z4", "develop@hcompany.com")) 

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
mysql> select * from member; 
+----+------------------------+------+
| id | email                  | dept |
+----+------------------------+------+
|  1 | president@hcompany.com | C1   |
|  2 | empoyee@hcompany.com   | Q2   |
|  3 | develop@hcompany.com   | B3   |
+----+------------------------+------+
3 rows in set (0.01 sec)

mysql> select * from member;
+----+------------------------+---------+
| id | email                  | dept    |
+----+------------------------+---------+
|  1 | president@hcompany.com | C1      |
|  2 | empoyee@hcompany.com   | Q2      |
|  3 | develop@hcompany.com   | Z4      |
+----+------------------------+---------+

 

 

 데이터 삭제

▶︎ 예제코드

코드 : 
# pymysql을 import합니다.
import pymysql

# 컨넥션 객체를 선언합니다.
conn_db = pymysql.connect(
host='10.30.224.200',
user='root',
password='admin1234',
charset='utf8',
db='sampledb'
) 


# 커서를 선언합니다.
cursor = conn_db.cursor() 

# SQL 템플릿을 만듭니다.
sql = "DELETE FROM member WHERE email = %s" 

# SQL 템플릿을 커서에 맵핑 후 수행합니다.
cursor.execute(sql, ("empoyee@hcompany.com")) 

# 커밋을 수행합니다.
conn_db.commit()

# 컨넥션 객체를 닫습니다. 
conn_db.close()

결과 : 
mysql> select * from member; 
+----+------------------------+------+
| id | email                  | dept |
+----+------------------------+------+
|  1 | president@hcompany.com | C1   |
|  2 | empoyee@hcompany.com   | Q2   |
|  3 | develop@limsee.com     | B3   |
+----+------------------------+------+
3 rows in set (0.00 sec)

mysql> select * from member;
+----+------------------------+------+
| id | email                  | dept |
+----+------------------------+------+
|  1 | president@hcompany.com | C1   |
|  3 | develop@limsee.com     | B3   |
+----+------------------------+------+
2 rows in set (0.00 sec)

 

 

반응형