(1) 기본 용어/개념
* connection: python과 mariadb를 연결하는 객체
import pymysql
connection = pymysql.connect(host='host', user='user', password='password', databse='dbname')
* cursor: 쿼리를 실행하고 결과를 가져오는데 사용되는 객체, SQL 문을 실행하고 결과를 처리할 수 있게 지원한다.
cursor = connection.cursor()
* query: SQL 구문을 작성하고 cursor를 사용하여 실행한다.
cursor.execute("SELECT * FROM table_name")
* commit: 데이터베이스 트랜젝션을 확정하는 작업으로 데이터 변경이 필요한 insert, update, delete 작업을 수행한 후 반영을 위해 commit을 실행해야 한다.
connection.commit()
* rollback: 트랜젝션에서 발생한 모든 변경 사항을 취소하는 작업으로, 오류가 발생하거난 변경 사항 저장을 원하지 않는 경우 사용한다.
connection.rollback()
(2) insert 예제
import pymysql
connection = pymysql.connect(host='host', user='user', password='password', database='dbname')
cursor = connection.cursor()
sql = "INSERT INTO tablename (column1, column2) VALUES (%s, %s)"
values = ("value1", "value2")
cursor.execute(sql, values)
connection.commit()
cursor.close()
connection.cose()
string이 아닌 데이터 형식을 사용하더라도 아래와 같이 위 구문을 그대로 사용 가능하다.
sql = """
INSERT INTO tablename (column1, column2, column3, column4)
VALUES (%s, %s, %s, %s)
"""
values = ("My name", 30, 180.1, datetime(2024, 6, 5, 14, 30, 00))
cursor.execute(sql, values)
(3) select 예제
connection = ...
cursor = ...
sql = "SELECT * FROM tablename"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
connection.close()
(4) update 예제
connection = ...
cursor = ...
sql = "UPDATE tablename SET column1 = %s where column2 = %s"
values = ("new_value", "value2")
cursor.execute(sql, values)
connection.commit()
cursor.close()
connection.close()
(5) delete 예제
connection = ...
cursor = ...
sql = "DELETE FROM tablename where column1 = %s"
values = ("value1")
cursor.execute(sql, values)
connection.commit()
cursor.close()
connection.close()
(6) transaction과 commit
cursor를 이용하여 sql 문을 execute 한 후 commit을 실행하지 않으면, 변경 사항이 데이터베이스에 반영되지 않는다. 이는 insert, update, delete query에 적용되는데, 이 query들은 transaction의 일부로 처리 되기 때문이다.
* transaction: 여러개의 데이터베이스 작업을 하나로 묶는 것을 말한다. 트랜젝션은 원자성을 보장하기 때문에, 트랜젝션 내부의 모든 데이터베이스 작업이 성공해야만 결과가 데이터베이스에 반영된다. 하나라도 실패하면 전체 트랜젝션이 롤백된다.
* commit: 트랜젝션을 종료하고, 모든 변경사항을 영구적으로 데이터베이스에 반영하는 동작이다.
* rollback: 트랜젝션 내의 모든 변경사항을 취소하고 데이터베이스를 트랜젝션 이전 상태로 돌려 놓는다.
예를 들어 insert 구문 실행 후 commit을 호출하지 않고 cursor.close(), connection.close()가 호출 되면, 자동으로 트랜젝션이 롤백되어 변경 사항이 취소 된다. select문은 트랜젝션에 속하지 않기 때문에 commit을 호출할 필요가 없다.
'Software Engineering > Python' 카테고리의 다른 글
| sample project 연습 (1) | 2024.06.20 |
|---|---|
| timer 유틸리티 클래스 (0) | 2024.06.19 |
| pydantic을 사용하여 환경변수 로딩하기 (1) | 2024.06.09 |
| fastapi post 요청으로 logging 레벨 변경하기 (3) | 2024.06.09 |
| fastapi get 요청으로 app 종료하기 (0) | 2024.06.09 |