MySQL DB python 연동하는 법
pip install mysql-connector-python
mysql-connector-python 을 설치한다.
import mysql.connector
mysql.connector 을 import 한다.
#pip install mysql-connector-python
import mysql.connector
connection = mysql.connector.connect( # connection 이라는 객체로 반환
host='localhost', # 접근할 mysql 서버 주소
user='ohgiraffers', # mysql에서 생성한 user name
password='ohgiraffers',# mysql에서 생성한 password
database='menudb' # 접근할 데이터베이스 스키마
)
if connection.is_connected():
print("MySQL에 성공적으로 연결되었습니다.")
사용할 database에 연결한다. 연결되었는 지 확인을 위해서는 connection.is_connected() 사용.
아래는 간단한 예제이다. 이 코드를 그대로 사용하려면
2025.02.19 - [Database/Mysql] - MySQL 명령어 : SELECT, ORDER BY, WHERE, DISTINCT
위의 링크의 menudb를 사용하면 된다.
-c 삽입
#pip install mysql-connector-python
import mysql.connector
connection = mysql.connector.connect( # connection 이라는 객체로 반환
host='localhost', # 접근할 mysql 서버 주소
user='ohgiraffers', # mysql에서 생성한 user name
password='ohgiraffers',# mysql에서 생성한 password
database='menudb' # 접근할 데이터베이스 스키마
)
if connection.is_connected():
print("MySQL에 성공적으로 연결되었습니다.")
cursor = connection.cursor()
sql = "INSERT INTO tbl_menu(menu_name, menu_price, category_code, orderable_status) VALUES (%s, %s, %s, %s)"
values = ('쌀국수', 12000, 4, 'Y')
cursor.execute(sql, values)
print(f'{cursor.rowcount}개의 행을 삽입하였습니다.') #삽입한 행 수
connection.commit() # -r 파일에서 조회가 되기 위해서는 반드시 사용해야함.
cursor.close()
connection.close() # 연결이 끝나면 close
-r 읽기
#pip install mysql-connector-python
import mysql.connector
connection = mysql.connector.connect( # connection 이라는 객체로 반환
host='localhost', # 접근할 mysql 서버 주소
user='ohgiraffers', # mysql에서 생성한 user name
password='ohgiraffers',# mysql에서 생성한 password
database='menudb' # 접근할 데이터베이스 스키마
)
if connection.is_connected():
print("MySQL에 성공적으로 연결되었습니다.")
cursor = connection.cursor() #데이터 작업을 위한 커서 객체를 생성해서 반환.
cursor.execute("SELECT menu_code, menu_name, menu_price FROM tbl_menu")
result = cursor.fetchall() # fetchall - 위에 있는 쿼리를 수행해서 받은 결과를 전부 가져옴.
# print(result)
for row in result: # row = 한 행의 결과
print('menucode:',row[0],'/', 'menuname:', row[1], 'menuprice:', row[2])
cursor.close()
connection.close() # 연결이 끝나면 close
-d 삭제
#pip install mysql-connector-python
import mysql.connector
connection = mysql.connector.connect( # connection 이라는 객체로 반환
host='localhost', # 접근할 mysql 서버 주소
user='ohgiraffers', # mysql에서 생성한 user name
password='ohgiraffers',# mysql에서 생성한 password
database='menudb' # 접근할 데이터베이스 스키마
)
if connection.is_connected():
print("MySQL에 성공적으로 연결되었습니다.")
# menu_code가 100번 이상인 메뉴 삭제
# 다른 방법
# sql = "DELETE FROM tbl_menu WHERE menu_code > %s"
# values = (99,) # (99)로 주면 99를 준 것과 같고 튜플을 줘야하므로 요소가 하나인 경우 (99,)와 같은 형태로 사용.
# cursor = connection.cursor()
# cursor.execute(sql, values)
# connection.commit()
# print(f'{cursor.rowcount}개의 행을 삭제하였습니다.')
# cursor.close()
# connection.close()
cursor = connection.cursor() #데이터 작업을 위한 커서 객체를 생성해서 반환.
cursor.execute("DELETE FROM tbl_menu WHERE menu_code >= 100")
connection.commit()
cursor.close()
connection.close() # 연결이 끝나면 close
-u 수정
import mysql.connector
connection = mysql.connector.connect( # connection 이라는 객체로 반환
host='localhost', # 접근할 mysql 서버 주소
user='ohgiraffers', # mysql에서 생성한 user name
password='ohgiraffers',# mysql에서 생성한 password
database='menudb' # 접근할 데이터베이스 스키마
)
if connection.is_connected():
print("MySQL에 성공적으로 연결되었습니다.")
# 1번 메뉴를 나의 점심 메뉴로 메뉴명과 가격을 수정
# 다른 방법
# sql = "UPDATE tbl_menu SET menu_name = %s, menu_price = %s WHERE menu_code = 1"
# values = ("제육볶음", 10000)
# cursor = connection.cursor()
# cursor.execute(sql,values)
# connection.commit()
# print(f'{cursor.rowcount}개의 행이 업데이트 되었습니다.')
# cursor.close()
# connection.close()
cursor = connection.cursor()
cursor.execute("UPDATE tbl_menu SET menu_code = 1, menu_name = '떡볶이', menu_price = 5000 WHERE menu_code = 4")
connection.commit()
cursor.close()
connection.close() # 연결이 끝나면 close
'Database > Mysql' 카테고리의 다른 글
MySQL 명령어 : JOIN (0) | 2025.02.20 |
---|---|
MySQL 명령어 : DML(INSERT, UPDATE, DELETE, REPLACE) (0) | 2025.02.20 |
MySQL 명령어 : LIMIT, GROUPING (0) | 2025.02.20 |
MySQL 명령어 : SELECT, ORDER BY, WHERE, DISTINCT (0) | 2025.02.19 |
Create USER & DATABASE (0) | 2025.02.19 |