杰瑞科技汇

executescript Python如何执行脚本?

Of course! The term executescript in Python is most commonly associated with the sqlite3 module, which is used to interact with SQLite databases. It's a powerful method for running multiple SQL statements at once.

executescript Python如何执行脚本?-图1
(图片来源网络,侵删)

Let's break it down, starting with the most common use case and then covering other, more advanced scenarios.


The Primary Use Case: sqlite3.executescript()

This is the standard and recommended way to execute a multi-statement SQL script in an SQLite database. The key advantage is that it handles the creation of a transaction for you, rolling back all changes if any single statement in the script fails.

Syntax and Purpose

sqlite3.executescript(sql_script)
  • sql_script: A string containing one or more SQL statements, separated by semicolons ().
  • Return Value: This method does not return a cursor. It's designed for running commands that don't return data, like creating tables, inserting initial data, or setting up a database schema.

Key Characteristics:

  1. Transaction Management: It implicitly wraps the entire script in a transaction. If any statement fails, the whole transaction is rolled back. This is crucial for maintaining data integrity.
  2. No Result Set: It is not used for SELECT queries that return data. For that, you use cursor.execute().
  3. Auto-Commit: The transaction is automatically committed if all statements execute successfully.

Example: Setting up a database

Let's create a simple database, a table, and insert some data.

import sqlite3
import os
# Define the SQL script
# This script creates a table and inserts two rows.
setup_script = """
-- Create a table for users if it doesn't already exist
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    age INTEGER
);
-- Insert some initial data
INSERT INTO users (name, email, age) VALUES
('Alice', 'alice@example.com', 30),
('Bob', 'bob@example.com', 25);
"""
# --- Main execution ---
db_file = 'my_database.db'
# Remove the old database file if it exists to start fresh
if os.path.exists(db_file):
    os.remove(db_file)
try:
    # 1. Connect to the database (this will create the file if it doesn't exist)
    conn = sqlite3.connect(db_file)
    print(f"Successfully connected to '{db_file}'")
    # 2. Get a cursor object
    cursor = conn.cursor()
    # 3. Execute the entire script
    print("\nExecuting SQL script...")
    cursor.executescript(setup_script)
    print("Script executed successfully.")
    # 4. Verify the data was inserted (using cursor.execute for a SELECT query)
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
    print("\n--- Current Data in 'users' table ---")
    for row in rows:
        print(row)
    # 5. Close the connection
    conn.close()
except sqlite3.Error as e:
    print(f"An error occurred: {e}")
    if conn:
        conn.rollback() # executescript does this automatically, but good practice to know
        conn.close()

Output of the script:

executescript Python如何执行脚本?-图2
(图片来源网络,侵删)
Successfully connected to 'my_database.db'
Executing SQL script...
Script executed successfully.
--- Current Data in 'users' table ---
(1, 'Alice', 'alice@example.com', 30)
(2, 'Bob', 'bob@example.com', 25)

Alternative for Other Databases (e.g., PostgreSQL, MySQL)

The executescript method is specific to sqlite3. For other database libraries like psycopg2 (PostgreSQL) or mysql-connector-python, you don't have a direct equivalent. The standard approach is to use the cursor's execute() method within a transaction block.

The logic is the same: combine statements with semicolons and manage the transaction manually.

Example with psycopg2 (PostgreSQL)

import psycopg2
# Define the SQL script
setup_script = """
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL
);
INSERT INTO users (name, email) VALUES
('Charlie', 'charlie@example.com'),
('Diana', 'diana@example.com');
"""
# Connection details (replace with your own)
DB_NAME = "mydb"
USER = "myuser"
PASSWORD = "mypassword"
HOST = "localhost"
PORT = "5432"
try:
    # Connect to the PostgreSQL database
    conn = psycopg2.connect(
        dbname=DB_NAME, user=USER, password=PASSWORD, host=HOST, port=PORT
    )
    print("Successfully connected to PostgreSQL.")
    # Get a cursor
    cursor = conn.cursor()
    # Manually start a transaction
    conn.autocommit = False
    print("\nExecuting SQL script...")
    # Execute the multi-statement script
    cursor.execute(setup_script)
    print("Script executed successfully.")
    # Commit the transaction
    conn.commit()
    print("Transaction committed.")
    # Verify the data
    cursor.execute("SELECT * FROM users;")
    rows = cursor.fetchall()
    print("\n--- Current Data in 'users' table ---")
    for row in rows:
        print(row)
    cursor.close()
    conn.close()
except psycopg2.Error as e:
    print(f"An error occurred: {e}")
    if conn:
        # Roll back the transaction in case of error
        conn.rollback()
        print("Transaction rolled back.")
    conn.close()

Advanced Python: exec() and executescript() for Dynamic Code Execution

It's important to distinguish between the database method and the core Python built-in functions.

exec() vs. eval()

  • exec(): Executes a string as a Python statement or a block of statements. It can have side effects (e.g., modifying variables, defining functions). It returns None.
  • eval(): Evaluates a string as a Python expression and returns the result of the expression. It cannot execute statements.

exec() Example

This is extremely powerful but also extremely dangerous if used with untrusted input, as it can execute arbitrary code.

executescript Python如何执行脚本?-图3
(图片来源网络,侵删)
# --- Safe Example: Executing a known code block ---
code_block = """
x = 10
y = 20
sum_result = x + y
print(f"Inside the exec block: x={x}, y={y}, sum={sum_result}")
"""
# The variables defined inside exec are not accessible outside by default
# To make them accessible, pass a dictionary as the 'globals' argument.
local_vars = {}
exec(code_block, globals(), local_vars)
print("\nAfter the exec block:")
print(f"Value of 'sum_result' from local_vars: {local_vars.get('sum_result')}")
print(f"Value of 'x' from globals: {globals().get('x')}")
# --- DANGER ZONE: Executing untrusted input ---
# NEVER do this with user input from a web form, a file, etc.
# user_input = "__import__('os').system('echo \"This command was executed!\"')" # Malicious input
# exec(user_input) # This would run the system command!
# print("If you see a message above, the code was executed.")

Summary: Which one to use?

Method Module Purpose When to Use
executescript() sqlite3 Run a multi-statement SQL script against an SQLite database. Setting up database schemas, creating tables, inserting initial data.
cursor.execute() psycopg2, mysql-connector, sqlite3 Run a single SQL statement. For SELECT, it returns a result set. The standard way to run any SQL query. For other databases, you combine statements and manage transactions manually.
exec() Built-in Execute a string as dynamic Python code. Metaprogramming, dynamic code generation, or running code from a configuration file. Use with extreme caution.
分享:
扫描分享到社交APP
上一篇
下一篇