Python PostgreSQL – 使用提交和回滚的事务管理
在本文中,我们将了解如何使用 Commit 和 Rollback 进行事务管理。
在 pyscopg 中,psycopg 中的连接类负责处理事务。当您使用游标对象向 PostgreSQL 数据库发出第一条 SQL 语句时,psycopg 会生成一个新事务。从那时起,Psycopg 将在同一事务中执行所有后续语句。如果任何语句失败,Psycopg 将停止事务。 Commit() 和 rollback() 是连接类的两种方法,可用于停止事务。 commit()函数用于永久提交对 PostgreSQL 数据库的所有更改。您还可以使用 rollback()函数撤消所做的任何修改。
犯罪:
connection.commit()
回滚:
connection.rollback()
以下是如何在 psycopg 中处理事务的示例,这是处理它的最基本方法。
我们正在处理的数据库中的表如下所示:
单击此处查看和下载 CSV 文件。
在 PostgreSQL 中创建 sales 表并导入 CSV 文件:
Python3
# import packages
import psycopg2
import pandas as pd
from sqlalchemy import create_engine
# establish connections
conn_string = 'postgres://postgres:pass@127.0.0.1/SuperMart'
db = create_engine(conn_string)
conn = db.connect()
conn1 = psycopg2.connect(
database="SuperMart", user='postgres',
password='pass', host='127.0.0.1', port='5432'
)
conn1.autocommit = True
cursor = conn1.cursor()
# drop table if it already exists
cursor.execute('drop table if exists sales')
sql = '''CREATE TABLE sales(Order_Line int,\
Order_ID char(20),Order_Date Date,Ship_Date Date,\
Ship_Mode char(20) ,Customer_ID char(20),Product_ID char(20),\
Sales decimal,Quantity int,Discount decimal,Profit decimal);'''
cursor.execute(sql)
# import the csv file to create a dataframe
data = pd.read_csv("Sales.csv")
# converting data to sql
data.to_sql('sales', conn, if_exists='replace')
# fetching all rows
sql1 = '''select * from sales;'''
cursor.execute(sql1)
for i in cursor.fetchall():
print(i)
conn1.commit()
conn1.close()
Python3
# import packages
import psycopg2
try:
# establish a connection to the database
connection = psycopg2.connect(
database="SuperMart", user='postgres',
password='PASS', host='127.0.0.1', port='5432')
# disable autocommit mode
connection.autocommit = False
# creating a cursor object
cursor = connection.cursor()
# querying data
query = """select sales from sales where\
Order_ID = 'CA-2016-152156'"""
cursor.execute(query)
record = cursor.fetchall()
sum = 0
for i in record:
sum = sum+i[0]
print("total sales from the order id CA-2016-152156 is : " + str(sum))
# commiting changes
connection.commit()
print("successfully finished the transaction ")
except (Exception, psycopg2.DatabaseError) as error:
print("Error in transaction, reverting all changes using rollback ", error)
connection.rollback()
finally:
# closing database connection.
if connection:
# closing connections
cursor.close()
connection.close()
print("PostgreSQL database connection is closed")
Python3
# import packages
import psycopg2
try:
# establish a connection to the database
connection = psycopg2.connect(database="SuperMart",
user='postgres',
password='sherlockedisi',
host='127.0.0.1',
port='5432')
# disable autocommit mode
connection.autocommit = False
# creating a cursor object
cursor = connection.cursor()
# querying data
query = """select sales from sales1 \
where Order_ID = 'CA-2016-1521591'"""
cursor.execute(query)
# fetching data
record = cursor.fetchall()
sum = 0
for i in record:
sum = sum+i[0]
print("total sales from the order\
id CA-2016-152159 is : " + str(sum))
# commiting changes
connection.commit()
print("successfully finished the transaction ")
except (Exception, psycopg2.DatabaseError) as error:
print("Error in transaction, reverting all\
changes using rollback, error is : ", error)
connection.rollback()
finally:
# closing database connection.
if connection:
# closing connections
cursor.close()
connection.close()
print("PostgreSQL database connection is closed")
示例 1:成功交易的示例
代码从导入包开始,建立与数据库的连接,我们必须确保 connection.autocommit 为 false,因为默认情况下它为 True,它预先提交所有更改,我们不能使用 rollback() 回到以前的状态.游标是使用 connection.cursor() 方法创建的。查询和获取数据。计算特定 order_id 的销售额。由于 SQL 语句没有任何错误,因此事务成功完成。
Python3
# import packages
import psycopg2
try:
# establish a connection to the database
connection = psycopg2.connect(
database="SuperMart", user='postgres',
password='PASS', host='127.0.0.1', port='5432')
# disable autocommit mode
connection.autocommit = False
# creating a cursor object
cursor = connection.cursor()
# querying data
query = """select sales from sales where\
Order_ID = 'CA-2016-152156'"""
cursor.execute(query)
record = cursor.fetchall()
sum = 0
for i in record:
sum = sum+i[0]
print("total sales from the order id CA-2016-152156 is : " + str(sum))
# commiting changes
connection.commit()
print("successfully finished the transaction ")
except (Exception, psycopg2.DatabaseError) as error:
print("Error in transaction, reverting all changes using rollback ", error)
connection.rollback()
finally:
# closing database connection.
if connection:
# closing connections
cursor.close()
connection.close()
print("PostgreSQL database connection is closed")
输出:
total sales from the order id CA-2016-152156 is : 993.9000000000001
successfully finished the transaction
PostgreSQL database connection is closed
示例 2:不成功事务的示例
代码与前面的代码类似,只是在 SQL 语句中给出了错误的表名,因为它不正确,所有更改都使用 rollback() 方法恢复或撤消并关闭连接。
Python3
# import packages
import psycopg2
try:
# establish a connection to the database
connection = psycopg2.connect(database="SuperMart",
user='postgres',
password='sherlockedisi',
host='127.0.0.1',
port='5432')
# disable autocommit mode
connection.autocommit = False
# creating a cursor object
cursor = connection.cursor()
# querying data
query = """select sales from sales1 \
where Order_ID = 'CA-2016-1521591'"""
cursor.execute(query)
# fetching data
record = cursor.fetchall()
sum = 0
for i in record:
sum = sum+i[0]
print("total sales from the order\
id CA-2016-152159 is : " + str(sum))
# commiting changes
connection.commit()
print("successfully finished the transaction ")
except (Exception, psycopg2.DatabaseError) as error:
print("Error in transaction, reverting all\
changes using rollback, error is : ", error)
connection.rollback()
finally:
# closing database connection.
if connection:
# closing connections
cursor.close()
connection.close()
print("PostgreSQL database connection is closed")
输出:
Error in transaction, reverting all changes using rollback, error is : relation “sales1” does not exist
LINE 1: select sales from sales1 where order_id = ‘CA-2016-1521591’
^