杰瑞科技汇

Python SQLite update操作如何正确执行?

Of course! Here is a comprehensive guide on how to update data in an SQLite database using Python, covering the basic steps, best practices, and common examples.

Python SQLite update操作如何正确执行?-图1
(图片来源网络,侵删)

The Core Concept: The UPDATE Statement

To update data in a database, you use SQL's UPDATE statement. The basic syntax is:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

CRITICAL WARNING: The WHERE clause is essential. If you forget it, you will update every single row in the table! Always run your UPDATE query as a SELECT statement first to verify which rows will be affected.


Step-by-Step Guide in Python

Here is the complete, step-by-step process for updating data.

Step 1: Import the sqlite3 Module

This module is part of Python's standard library, so no installation is needed.

Python SQLite update操作如何正确执行?-图2
(图片来源网络,侵删)
import sqlite3

Step 2: Connect to the Database

This will create the database file if it doesn't exist, or connect to it if it does.

# Connect to the SQLite database (or create it)
conn = sqlite3.connect('mydatabase.db')

Step 3: Create a Cursor Object

A cursor is like a pointer that allows you to execute SQL commands.

cursor = conn.cursor()

Step 4: Write and Execute the UPDATE Query

This is where you define your SQL statement. We'll use a placeholder to prevent SQL injection, which is a critical security practice.

# SQL query to update a record
# We are updating the 'email' for the user with 'id' = 2
sql_update_query = "UPDATE employees SET email = ? WHERE id = ?"

Step 5: Commit the Changes

After executing the query, you must call conn.commit() to save the changes to the database file. If you don't, the changes will be lost when the connection is closed.

conn.commit()

Step 6: Close the Connection

It's good practice to close the connection when you're done.

conn.close()

Complete, Runnable Example

Let's put it all together. This example will:

  1. Create a database and a table.
  2. Insert some initial data.
  3. Update a specific record.
  4. Verify the update by selecting the data.
import sqlite3
def update_employee_email(employee_id, new_email):
    """Updates the email of a specific employee in the database."""
    try:
        # 1. Connect to the database
        conn = sqlite3.connect('company.db')
        cursor = conn.cursor()
        # 2. Define the SQL query with placeholders
        sql_update_query = "UPDATE employees SET email = ? WHERE id = ?"
        # 3. Execute the query with the parameters
        # Using a tuple to pass the values
        cursor.execute(sql_update_query, (new_email, employee_id))
        # 4. Commit the changes to the database
        conn.commit()
        print(f"Successfully updated email for employee ID {employee_id}")
    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        # 5. Close the connection
        if conn:
            conn.close()
def show_all_employees():
    """Displays all records in the employees table."""
    try:
        conn = sqlite3.connect('company.db')
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM employees")
        records = cursor.fetchall()
        print("\n--- Current Employee Records ---")
        for row in records:
            print(row)
        print("--------------------------------\n")
    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        if conn:
            conn.close()
# --- Main part of the script ---
if __name__ == "__main__":
    # Setup: Create the table and insert initial data
    try:
        conn = sqlite3.connect('company.db')
        cursor = conn.cursor()
        # Create table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS employees (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT NOT NULL,
                department TEXT
            )
        ''')
        # Insert some data (only if the table is empty)
        cursor.execute("SELECT COUNT(*) FROM employees")
        if cursor.fetchone()[0] == 0:
            cursor.executemany("INSERT INTO employees (name, email, department) VALUES (?, ?, ?)", [
                ('Alice', 'alice@example.com', 'Engineering'),
                ('Bob', 'bob_old@example.com', 'Marketing'),
                ('Charlie', 'charlie@example.com', 'Sales')
            ])
            conn.commit()
            print("Initial data inserted.")
    except sqlite3.Error as e:
        print(f"Setup error: {e}")
    finally:
        if conn:
            conn.close()
    # --- Perform the Update ---
    print("\n--- Before Update ---")
    show_all_employees()
    # Update Bob's email
    update_employee_email(employee_id=2, new_email='bob_new@example.com')
    print("--- After Update ---")
    show_all_employees()

Best Practices

Use Placeholders () to Prevent SQL Injection

NEVER use f-strings or the operator to insert variables directly into your SQL query. This makes your application vulnerable to SQL injection attacks.

BAD (Vulnerable):

user_id = 2
new_email = "new@example.com"
# DANGEROUS! This allows malicious input to alter the SQL command.
query = f"UPDATE users SET email = '{new_email}' WHERE id = {user_id}"
cursor.execute(query)

GOOD (Secure):

user_id = 2
new_email = "new@example.com"
# SAFE. The library handles the escaping.
query = "UPDATE users SET email = ? WHERE id = ?"
cursor.execute(query, (new_email, user_id))

Use try...except...finally for Robust Code

Database connections and operations can fail for many reasons (e.g., file permissions, disk full). The try...except...finally block ensures that your program handles errors gracefully and that the database connection is always closed, even if an error occurs.

Check How Many Rows Were Affected

The cursor.execute() method returns a special object that has a rowcount attribute. This tells you how many rows were updated by your query.

cursor.execute(sql_update_query, (new_email, employee_id))
print(f"{cursor.rowcount} row(s) were updated.")

This is useful for confirming that your WHERE clause matched the expected number of rows.

Use executemany() for Bulk Updates

If you need to update multiple rows based on a list of data, executemany() is much more efficient than looping and calling execute() each time.

updates = [
    (1, 'john.doe@new.com'),  # Update ID 1
    (3, 'jane.smith@new.com')  # Update ID 3
]
sql = "UPDATE employees SET email = ? WHERE id = ?"
cursor.executemany(sql, updates)
conn.commit()
print(f"{cursor.rowcount} rows were updated in bulk.")
分享:
扫描分享到社交APP
上一篇
下一篇