기본 구조
import mysql.connector
# local이라는 변수에 넣어서 connect 실행하기
local = mysql.connector.connect(
host = "hostname",
user = "username",
password = "******"
)
# close 연결 종료하기
local.close()
🚨 사용이 끝나면 꼭 연결 종료해주기!
# 원격 연결
remote = mysql.connector.connect(
host = "database-11.chomm6uam1ai.us-east-2.rds.amazonaws.com",
port = ****,
user = "username",
password = "********"
)
# 연결 종료
remote.close()
- local 로컬
import mysql.connector
local = mysql.connector.connect(
host = "localhost",
user = "root",
password = "*****",
database = "zerobase"
)
local.close()
- remote 원격
remote = mysql.connector.connect(
host = "database-11.chomm6uam1ai.us-east-2.rds.amazonaws.com",
port = 3306,
user = "root",
password = "********",
database = "zerobase"
)
remote.close()
✍️ database 추가해주면 됨!
remote = mysql.connector.connect(
host = "address",
port = ****,
user = "username",
password = "*******",
database = "zerobase"
)
cur = remote.cursor()
cur.execute("CREATE TABLE sql_file (id int, filename varchar(16))")
remote.close()
remote = mysql.connector.connect(
host = "address",
port = ****,
user = "username",
password = "*******",
database = "zerobase"
)
cur = remote.cursor()
cur.execute("DROP TABLE sql_file")
remote.close()
mydb = mysql.connector.connect(
host = "hostname",
user = "username",
password = "*******",
database = "databasename"
)
mycursor = mydb.cursor()
sql = open("filename.sql").read()
mycursor.execute(sql)
🚨 하.지.만
SQL file에 쿼리가 여러개가 존재한다면 옵션 필요!!
✍️ " multi = TRUE"
mydb = mysql.connector.connect(
host = "hostname",
user = "username",
password = "*******",
database = "databasename"
)
mycursor = mydb.cursor()
sql = open("test04.sql").read()
for result_iterator in cur.execute(sql, multi=True):
if result_iterator.with_rows:
print(result_iterator.fetchall())
else:
print(result_iterator.statement)
remote.commit()
remote.close()
✍️ multi = True 옵션 추가해주기
✍️ fetch all : 쿼리 실행한 다음에 결과값이 row를 포함하고 있으면 fetch all 해서 출력해 쿼리 하나하나 실행해주기
mycursor.execute(<query>)
result = mucursor.fetchall()
for data in result:
print(data)
👀 실행하는 쿼리가 아니라 조회하는 select문을 사용하는 경우,
존재하는 데이터를 가져올 때, 'fetch all'을 써서 데이터를 변수(result)에 담을 수가 있음.
👀 그리고 변수에 담은 데이터를 바로 출력하면 한꺼번에 출력이 되고 for문을 쓰면 row마다 출력이 되도록 할 수 있음.
✍️ 읽어올 데이터 양이 많은 경우 buffered=True 옵션 추가
remote = mysql.connector.connect(
host = "address",
port = ****,
user = "root",
password = "*******",
database = "zerobase"
)
cur = remote.cursor(buffered=True)
cur.execute("select * from sql_file")
result = cur.fetchall()
print("without_for", result)
for result_iterator in result:
print("with", result_iterator)
remote.close()
fetchall()
그냥 fetchall()로 테이블 데이터 가져온 경우
fetchall() + for문
for문과 함께 fetchall()로 테이블 데이터 가져온 경우
- result를 읽어온 결과를
pandas 데이터프레임으로 변환해주고
df라는 변수로 만들고 데이터프레임 상단을 조회하기
df = pd.DataFrame(result)
df.head()
🚨 result라는 변수에 담아서 여러 row 출력하기
- fetchall() + for문
- pandas 데이터프레임 사용하기