Python AWS Lambda:如何将RDS Aurora查询作为原子事务执行?
我在AWS Lambda函数中有以下Python代码,我希望RDS Aurora DB上的查询以原子方式运行,即运行all或none。Python AWS Lambda:如何将RDS Aurora查询作为原子事务执行?,python,aws-lambda,Python,Aws Lambda,我在AWS Lambda函数中有以下Python代码,我希望RDS Aurora DB上的查询以原子方式运行,即运行all或none。conn.commit()语句能帮我做到这一点吗?如果没有,我如何才能做到这一点conn是我的数据库连接对象 # Connect to the DB conn = pymysql.connect(rds_host, user=username, passwd=password, db=db_name,
conn.commit()
语句能帮我做到这一点吗?如果没有,我如何才能做到这一点conn
是我的数据库连接对象
# 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()
多亏了基尔尼的评论,下面是答案
conn
来自哪里?SQLAlchemy,pg8000,还有别的吗?这就是管理事务(或不管理事务)的方法。@kielni,我在我的OP中指出这是我的DB连接对象,但我更新了帖子只是为了澄清它。谢谢。我没有使用过pymysql
,但您应该从中了解如何创建/提交/回滚事务(即运行all或none的group语句)。
# 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()