1. MySql connector 모듈 설치하기
pip install mysql-connector-python
2. Connection & Transaction
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
conn = mysql.connector.connect(host='localhost',
database='mysql',
user='xxx',
password='xxx')
conn.autocommit = False
cursor = conn.cursor()
# withdraw from account A
# sql_update_query = """Update codemaster set crt_emp = 'yyy' where codegrp = 'MST001'"""
# cursor.execute(sql_update_query)
# Deposit to account B
sql_update_query = """Update codemaster set crt_emp = 'XXX' where code = '001'"""
cursor.execute(sql_update_query)
print ("Record Updated successfully ")
#Commit your changes
conn.commit()
except mysql.connector.Error as error :
print("Failed to update record to database rollback: {}".format(error))
#reverting changes because of exception
conn.rollback()
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
print("connection is closed")