#连接对象
连接对象(Connection Object)用于表示和管理Python应用程序与数据库的单个连接。
# 对象创建方式
连接对象需通过connect()或poolname.acquire()创建。
# 连接属性
| 属性 | 说明 |
|---|---|
| Connection.autocommit | 事务自动提交模式,默认为False(手动提交)。 |
| Connection.username(只读) | 数据库用户名。 |
| Connection.dsn(只读) | 数据源名称。 |
# 连接方法
| 方法 | 说明 |
|---|---|
| Connection.close() | 立即关闭连接。 |
| Connection.commit() | 提交处理中的事务。当autocommit=True时,调用commit()会抛出异常。 |
| Connection.rollback() | 回滚处理中的事务。 |
| Connection.cursor() | 创建一个新的游标对象。 |
Note:
connection.isolation_level属性不存在。如需设置事务隔离级别,请通过SQL语句SET TRANSACTION ISOLATION LEVEL ...进行设置。autocommit=True时,调用commit()或rollback()均会抛出NotSupportedError。
# 完整示例
import yaspy
# 连接数据库
conn = yaspy.connect(dsn="sales/sales@192.168.1.2:1688")
# 查看连接属性
print(f'Autocommit: {conn.autocommit}')
print(f'Username: {conn.username}')
print(f'DSN: {conn.dsn}')
# 1. cursor() - 创建游标
cursor = conn.cursor()
# 创建测试表
cursor.execute("DROP TABLE IF EXISTS test_connection")
cursor.execute("""
CREATE TABLE test_connection (
id INT PRIMARY KEY,
name VARCHAR(50),
amount DECIMAL(10, 2)
)
""")
conn.commit()
print('Table created')
# 2. commit() - 提交事务
cursor.execute("INSERT INTO test_connection VALUES (1, 'Product A', 100.00)")
cursor.execute("INSERT INTO test_connection VALUES (2, 'Product B', 200.00)")
conn.commit()
print('Data committed via commit()')
# 3. 测试rollback()
# 插入数据但不提交
cursor.execute("INSERT INTO test_connection VALUES (3, 'Product C', 300.00)")
print('Data inserted (not committed yet)')
# 4. rollback() - 回滚未提交的事务
conn.rollback()
print('Transaction rolled back')
# 验证数据 - 应该只有2条记录
cursor.execute("SELECT * FROM test_connection")
rows = cursor.fetchall()
print(f'After rollback: {len(rows)} records')
# 重新插入数据并提交
cursor.execute("INSERT INTO test_connection VALUES (3, 'Product C', 300.00)")
conn.commit()
print('Data committed')
# 验证所有数据
cursor.execute("SELECT * FROM test_connection ORDER BY id")
rows = cursor.fetchall()
print(f'After commit: {len(rows)} records:')
for row in rows:
print(f' id={row[0]}, name={row[1]}, amount={row[2]}')
# 5. close() - 关闭游标
cursor.close()
print('Cursor closed')
# 清理测试表
conn.cursor().execute("DROP TABLE test_connection")
conn.commit()
print('Table cleaned up')
# 6. close() - 关闭连接
conn.close()
print('Connection closed')
执行:
Autocommit: False
Username: sales
DSN: 192.168.1.2:1688
Table created
Data committed via commit()
Data inserted (not committed yet)
Transaction rolled back
After rollback: 2 records
Data committed
After commit: 3 records:
id=1, name=Product A, amount=100.0
id=2, name=Product B, amount=200.0
id=3, name=Product C, amount=300.0
Cursor closed
Table cleaned up
Connection closed
其中:
- Autocommit: False:默认手动提交模式
- Username: sales:数据库用户名
- DSN: 192.168.1.2:1688:数据源名称(不含用户信息,仅为主机地址和端口)
- Table created:测试表创建成功
- Data committed via commit():通过commit()提交数据
- Data inserted (not committed yet):数据已插入但未提交
- Transaction rolled back:事务已回滚
- After rollback: 2 records:回滚后只有2条记录
- Data committed:数据已提交
- After commit: 3 records:提交后有3条记录
- Cursor closed:游标已关闭
- Table cleaned up:测试表清理完成
- Connection closed:连接已关闭

