์คํฐ๋ ๋ ธํธ (Python with MySQL)
๐ Python with MySQL
- mysql.connector library๋ฅผ ์ค์น ๋ฐ import
pip install mysql-connector-python
import mysql.connector
๐ mysql ์ ์ํ๊ธฐ
- ๋ก์ปฌ ํธ์คํธ๋ก ์ ์ํ๋ ๊ฒฝ์ฐ
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost"
user = "root"
password = "******"
)
- AWS ํ๊ฒฝ์ผ๋ก ์ ์ํ๋ ๊ฒฝ์ฐ
import mysql.connector
remote = mysql.connector.connect(
host = "end_point"
port = port_number
user = "admin"
password = "******"
)
- ์ฌ์ฉ์ ๋ค ํ๋ค๋ฉด connect๋ฅผ ์ข ๋ฃ
mydb.close()
๐ connect to database
- ํน์ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ๋ฐ๋ก ์ ์ํ๊ธฐ
- ๊ธฐ์กด connect ๋ฌธ์ database ํญ๋ชฉ์ด ์ถ๊ฐ๋๋ค.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost"
user = "root"
password = "******"
database = "db_name"
)
๐ execute๋ก ์ฟผ๋ฆฌ๋ฅผ ๋ ๋ ค๋ณด์
- execute๋ก sql์์ ์ฌ์ฉํ๋ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
remote = mysql.connector.connect(
host = "host_name"
port = "port_number"
user = "admin"
password = "******"
database = "db_name"
)
cur = remote.cursor()
cur.execute("query")
๐งท ์์
cur = remote.cursor()
cur.execute("create table sql_file (id int, filename varchar(16))")
cur = remote.cursor()
sql = open("test03.sql").read()
cur.execute(sql)
๐ ๋ณต์ ์ฟผ๋ฆฌ ์ฌ์ฉํ๊ธฐ
- execute ๋ฌธ์ ์ฟผ๋ฆฌ์ ํจ๊ป multi=True์ต์ ์ ์ค๋ค.
cur = remote.cursor()
sql = open("test04.sql").read()
for result_iterator in cur.execute(sql, multi=True): #multi=True ๊ฐ์ ์ค๋ค
if result_iterator.with_rows:
print(result_iterator.fetchall())
else:
print(result_iterator.statement)
remote.commit()
๐ fetchall()
- ๋ถ๋ฌ์ฌ ๋ฐ์ดํฐ๊ฐ ๋ง์ ๋, buffered = True ์ต์ ์ ์ค ์ ์๋ค
- fetchall() ํจ์๋ก ์ฟผ๋ฆฌ์ ๋ํ ์ถ๋ ฅ ๊ฐ์ return ๋ฐ์ ์ ์๋ค (๋ค์ํ ๊ฒ์ ํ ์ ์์!)
cur = remote.cursor(buffered=True)
cur.execute("query")
result = cur.fetchall()
result
for result_iterator in result:
print(result_iterator)
๐งท pandas ํํ๋ก ๋ถ๋ฌ์ค๊ธฐ
import pandas as pd
df = pd.DataFrame(result)
df.head()