[SQL 심화 (3)] Python with MySQL

이재은·2024년 6월 30일

✅목차

1. 실습환경 만들기
2. Python with MySQL
2-1. Install MySQL Driver
2-2. Create Connection
2-3. Close Database
2-4. Connect to Database
2-5. 🟡Execute SQL
2-6. Execute SQL File 1
2-7. 🟡Execute SQL File 2
2-8. 🟡Fetch All
3. Python with CSV
3-1. Read CSV
3-2. Zerobase에 연결
3-3. Cursor 만들기
3-4. 🟡INSERT 문 만들기
3-5. 🟡데이터 입력
3-6. Tip
4. Python with CSV 예제
5. 문제풀이(실습)

1. 실습환경 만들기

2. Python with MySQL

2-1. Install MySQL Driver

2-2. Create Connection

2-3. Close Database

2-4. Connect to Database

2-5. 🟡Execute SQL

  • 쿼리실행을 위한 코드 (커서 만들기= 실행)
mydb = mysql.connector.connect(
	host = "<hostname>",
    user = "<username>",
    password = "<password>",
    database = "<databasename>"
)

mycursor = mydb.cursor()
mycursor.execute(<query>);

2-6. Execute SQL File 1

  • SQL File을 실행하기 위한 코드 (open.read)
mydb = mysql.connector.connect(
	host = "<hostname>",
    user = "<username>",
    password = "<password>",
    database = "<databasename>"
)

mycursor = mydb.cursor()

sql = open("<filename>.sql").read()
mycursor.execute(sql)

2-7. 🟡Execute SQL File 2 (파일내 여러개 query)

  • SQL File 내에 Query 가 여러개 존재하는 경우
mydb = mysql.connector.connect(
	host = "<hostname>",
    user = "<username>",
    password = "<password>",
    database = "<databasename>"
)

mycursor = mydb.cursor()

sql = open("<filename>.sql").read()
result = mycursor.execute(sql, multi = True)
🟡 remote = mysql.connector.connect(
    host = "엔드포인트",
    port = 3306,
    user = "admin",
    password = "*******",
    database = "zerobase"
)

cur = remote.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: #검색결과가 아니면 statement
        print(result_iterator.statement)

remote.commit()
remote.close()

2-8. 🟡Fetch All

  • select 문 같은 경우 데이터를 가져옴
    그 데이터를 변수에 담을 때 (데이터 양이 많은경우가 많음)
  • sql_file 테이블 조회 (읽어올 데이터 양이 많은 경우 buffered=True)
cur = remote.cursor(buffered = True)
cur.execute(<query>)

result = cur.fetchall()
for data in result: #row로 찍힘
print(data)
  • 참고) 검색 결과를 Pandas로 읽기
import pandas as pd

df = pd.DataFrame(result)
df.head()

3. Python with CSV

3-1. Read CSV

3-2. Zerobase에 연결

3-3. Cursor 만들기

3-4. INSERT 문 만들기

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

cursor.execute(operation, params=None, multi=False)
(query, data, multi)
sql = "insert into police_station values (%s, %s)"

3-5. 데이터 입력(commit)

  • commit()은 database 에 적용하기 위한 명령
for i, row in df.iterrows():
    cursor.execute(sql, tuple(row))
    print(tuple(row))
    conn.commit()

3-6. Tip

4. Python with CSV 예제

  • 범죄현황

5. 문제풀이(실습)

profile
Dare to be an optimist

0개의 댓글