I have the following Python code in an AWS Lambda function, and I want the queries on an RDS Aurora DB to run atomically, that is, run all or run none. Will the conn.commit()
statement do that for me? If not how can I accomplish this? conn
is my DB connection object.
# Connect to the DB
conn = pymysql.connect(rds_host, user=username,
passwd=password, db=db_name,
connect_timeout=10)
# Run queries
with conn.cursor() as cur:
cur.execute("create table some_table_2020 like some_table;")
cur.execute("insert into some_table_2020 select * from some_table;")
cur.execute("rename table some_table to some_table_20200629;")
cur.execute("rename table some_table_2020 to some_table;")
conn.commit()
Thanks to kielni's comment, here's the answer, per Use Commit and Rollback to Manage MySQL Transactions in Python
# Connect to the DB
conn = pymysql.connect(rds_host, user=username,
passwd=password, db=db_name,
connect_timeout=10)
try:
# Run queries
with conn.cursor() as cur:
cur.execute("create table some_table_2020 like some_table;")
cur.execute("insert into some_table_2020 select * from some_table;")
cur.execute("rename table some_table to some_table_20200629;")
cur.execute("rename table some_table_2020 to some_table;")
conn.commit()
exception:
# Failed to commit changes in the DB, do rollback
conn.rollback()
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.