ZetCode

Python sqlite3.Cursor.connection 属性

上次修改时间:2025 年 4 月 15 日

本综合指南探讨 Python 的 sqlite3.Cursor.connection 属性,该属性提供从游标对象访问父连接的方法。

基本定义

sqlite3.Cursor.connection 属性是一个只读属性,返回创建游标的 sqlite3.Connection 对象。

当您需要从游标对象访问父连接时,例如用于事务控制或执行其他查询,此属性非常有用。

基本连接访问

此示例演示了从游标对象访问父连接。

basic_connection.py
import sqlite3

with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    
    # Access the parent connection
    parent_conn = cursor.connection
    
    # Verify it's the same connection
    print(parent_conn is conn)  # True
    
    cursor.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER)')
    cursor.connection.commit()  # Commit using cursor's connection

该示例展示了如何通过游标的 connection 属性访问父连接。我们验证它是否是同一个连接对象。

使用 connection 属性允许您执行连接操作,而无需保留对连接对象的单独引用。

通过游标进行事务控制

此示例展示了如何使用游标的连接进行事务控制。

transaction_control.py
import sqlite3

with sqlite3.connect('transactions.db') as conn:
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS accounts (id INTEGER, balance REAL)')
    
    try:
        cursor.execute("INSERT INTO accounts VALUES (1, 1000.0)")
        cursor.execute("INSERT INTO accounts VALUES (2, 500.0)")
        
        # Commit using cursor's connection
        cursor.connection.commit()
    except:
        # Rollback using cursor's connection
        cursor.connection.rollback()
        raise

在这里,我们使用游标的 connection 属性来提交或回滚事务。这在函数之间传递游标对象时非常有用。

即使您无法直接访问原始连接对象,此模式也能确保正确的事务处理。

创建新游标

此示例演示了从现有游标的连接创建新游标。

new_cursors.py
import sqlite3

with sqlite3.connect('multi_cursor.db') as conn:
    main_cursor = conn.cursor()
    main_cursor.execute('CREATE TABLE IF NOT EXISTS data (value TEXT)')
    
    # Create a new cursor from the first cursor's connection
    second_cursor = main_cursor.connection.cursor()
    second_cursor.execute("INSERT INTO data VALUES ('sample')")
    
    # Both cursors share the same connection
    main_cursor.execute("SELECT * FROM data")
    print(main_cursor.fetchall())  # [('sample',)]
    
    main_cursor.connection.commit()

该示例展示了如何从现有游标的连接创建其他游标。所有游标共享相同的连接和事务上下文。

当您需要多个游标,但当前作用域中只能访问一个游标对象时,此技术非常有用。

连接属性访问

此示例演示了通过游标访问连接属性。

connection_attributes.py
import sqlite3

with sqlite3.connect('attributes.db') as conn:
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()
    
    # Access connection attributes through cursor
    print(cursor.connection.row_factory)  # <class 'sqlite3.Row'>
    
    # Change isolation level through cursor
    cursor.connection.isolation_level = 'IMMEDIATE'
    
    cursor.execute('CREATE TABLE IF NOT EXISTS settings (param TEXT, value TEXT)')
    cursor.connection.commit()

在这里,我们通过游标的 connection 属性访问和修改连接属性。这包括行工厂和隔离级别。

即使您只能访问游标对象,此方法也允许您配置连接。

嵌套函数中的连接

此示例展示了在嵌套函数调用中使用 cursor.connection。

nested_functions.py
import sqlite3

def process_data(cursor):
    cursor.execute("INSERT INTO records (data) VALUES ('processed')")
    cursor.connection.commit()

def main():
    with sqlite3.connect('nested.db') as conn:
        cursor = conn.cursor()
        cursor.execute('CREATE TABLE IF NOT EXISTS records (data TEXT)')
        
        # Pass cursor to nested function
        process_data(cursor)
        
        cursor.execute("SELECT * FROM records")
        print(cursor.fetchall())

if __name__ == '__main__':
    main()

该示例演示了将游标传递给嵌套函数,然后该函数使用游标的连接来提交更改。

这种模式在较大的应用程序中很常见,在这些应用程序中,数据库操作分布在多个函数或模块中。

使用连接进行错误处理

此示例展示了使用游标的连接进行错误处理。

error_handling.py
import sqlite3

def safe_update(cursor, account_id, amount):
    try:
        cursor.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?",
                      (amount, account_id))
        cursor.connection.commit()
    except sqlite3.Error as e:
        cursor.connection.rollback()
        print(f"Error updating account {account_id}: {e}")
        raise

with sqlite3.connect('bank.db') as conn:
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS accounts
                     (id INTEGER PRIMARY KEY, balance REAL)''')
    
    # Insert test data
    cursor.execute("INSERT OR IGNORE INTO accounts VALUES (1, 1000.0)")
    conn.commit()
    
    # Perform safe update
    safe_update(cursor, 1, -200)
    
    cursor.execute("SELECT balance FROM accounts WHERE id = 1")
    print(f"New balance: {cursor.fetchone()[0]}")

该示例演示了一种强大的错误处理模式,其中嵌套函数使用游标的连接在发生错误时进行回滚。

即使操作在执行过程中部分失败,此方法也能确保数据一致性。

类方法中的连接

此示例展示了在类方法中使用 cursor.connection。

class_methods.py
import sqlite3

class DatabaseManager:
    def __init__(self, cursor):
        self.cursor = cursor
    
    def add_user(self, name, email):
        self.cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
                          (name, email))
        self.cursor.connection.commit()
    
    def get_users(self):
        self.cursor.execute("SELECT * FROM users")
        return self.cursor.fetchall()

with sqlite3.connect('users.db') as conn:
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS users
                     (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
    
    manager = DatabaseManager(cursor)
    manager.add_user('Alice', 'alice@example.com')
    
    print("All users:")
    for user in manager.get_users():
        print(user)

该示例演示了一个接收游标并使用其连接进行数据库操作的类。这是 ORM 和数据库包装器中的常见模式。

类方法可以执行完整的数据库操作,包括提交,而无需直接访问原始连接对象。

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程