杰瑞科技汇

python insertinto

Of course! The term "insertinto" in Python almost always refers to the SQL INSERT INTO statement, which is used to add new records to a table in a database.

python insertinto-图1
(图片来源网络,侵删)

Python doesn't have a built-in insertinto keyword. Instead, you use a database library (like sqlite3 for SQLite, psycopg2 for PostgreSQL, or mysql-connector-python for MySQL) to execute the SQL command.

I'll guide you through the process, starting with the most common and beginner-friendly database: SQLite, which comes built-in with Python.


The Core Concept: SQL INSERT INTO

First, let's look at the basic SQL syntax you'll be using:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
  • INSERT INTO table_name: Specifies the table you want to add data to.
  • (column1, column2, column3): Lists the columns you are providing data for. It's good practice to specify columns.
  • VALUES (value1, value2, value3): Provides the actual data values. The order must match the order of the columns.

Practical Example with SQLite (Built-in)

SQLite is a great choice for learning because it doesn't require a separate server. The database is stored in a single file on your computer.

python insertinto-图2
(图片来源网络,侵删)

Step 1: Create a Database and Table

Let's create a database file named mydatabase.db and a table called employees.

import sqlite3
# Connect to the database (it will be created if it doesn't exist)
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Create a table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT,
        salary REAL
    )
''')
print("Table 'employees' created or already exists.")
# Commit the changes and close the connection
conn.commit()
conn.close()

Step 2: Insert a Single Record

Now, let's insert one employee into the employees table.

import sqlite3
# Connect to the database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Define the data to insert
new_employee = ('Alice', 'Engineering', 90000.50)
# Use a parameterized query to prevent SQL injection
# The '?' are placeholders for the values
cursor.execute("INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", new_employee)
# Commit the transaction to save the changes
conn.commit()
print(f"Record inserted successfully. ID: {cursor.lastrowid}") # lastrowid gives you the ID of the new row
# Close the connection
conn.close()

Step 3: Insert Multiple Records at Once (More Efficient)

Inserting records one by one can be slow. You can use executemany() to insert a list of records in a single operation.

import sqlite3
# Connect to the database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
# Define a list of employees to insert
more_employees = [
    ('Bob', 'Marketing', 75000.00),
    ('Charlie', 'Sales', 80000.00),
    ('Diana', 'Engineering', 95000.75)
]
# Use executemany() to insert all records
cursor.executemany("INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", more_employees)
# Commit the transaction
conn.commit()
print(f"{cursor.rowcount} records inserted successfully.")
# Close the connection
conn.close()

Step 4: Verify the Data

Let's write a small script to fetch and print all the data to make sure our inserts worked.

python insertinto-图3
(图片来源网络,侵删)
import sqlite3
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
print("\n--- All Employees ---")
for row in rows:
    print(row)
conn.close()

Expected Output:

--- All Employees ---
(1, 'Alice', 'Engineering', 90000.5)
(2, 'Bob', 'Marketing', 75000.0)
(3, 'Charlie', 'Sales', 80000.0)
(4, 'Diana', 'Engineering', 95000.75)

Best Practices and Security

Parameterized Queries (The placeholders)

You should always use parameterized queries (like in SQLite or %s in other libraries) instead of formatting strings with f-strings or .format().

❌ WRONG (Vulnerable to SQL Injection):

# NEVER DO THIS!
name = "Eve"
department = "Hacking"
cursor.execute(f"INSERT INTO employees (name, department) VALUES ('{name}', '{department}')")

A malicious user could set name = "Robert'); DROP TABLE employees; --" and destroy your database.

✅ CORRECT (Safe):

# ALWAYS DO THIS!
name = "Eve"
department = "Hacking"
cursor.execute("INSERT INTO employees (name, department) VALUES (?, ?)", (name, department))

The database library safely handles the escaping of special characters, preventing SQL injection attacks.

The with Statement (Automatic Connection Handling)

Forgetting to conn.close() can lead to resource leaks. The with statement ensures the connection is automatically closed, even if errors occur.

import sqlite3
# The 'with' statement handles opening and closing the connection
with sqlite3.connect('mydatabase.db') as conn:
    cursor = conn.cursor()
    cursor.execute("INSERT INTO employees (name, department) VALUES (?, ?)", ('Frank', 'HR'))
    conn.commit() # Commit is still needed inside the 'with' block
print("Connection closed automatically.")

Example with a Different Library: psycopg2 (PostgreSQL)

The logic is identical, but the syntax for placeholders and connection details changes.

First, install the library: pip install psycopg2-binary

import psycopg2
# --- Connection Details ---
# Replace with your actual database details
DB_NAME = "mydb"
DB_USER = "myuser"
DB_PASS = "mypassword"
DB_HOST = "localhost"
DB_PORT = "5432"
try:
    # Connect to the PostgreSQL database
    conn = psycopg2.connect(
        dbname=DB_NAME,
        user=DB_USER,
        password=DB_PASS,
        host=DB_HOST,
        port=DB_PORT
    )
    cursor = conn.cursor()
    # Insert a single record using %s as the placeholder
    insert_query = "INSERT INTO employees (name, department, salary) VALUES (%s, %s, %s)"
    new_employee = ('Grace', 'Finance', 120000.00)
    cursor.execute(insert_query, new_employee)
    conn.commit()
    print(f"PostgreSQL: Record inserted successfully. ID: {cursor.fetchone()[0]}")
except (Exception, psycopg2.Error) as error:
    print(f"Error while connecting to PostgreSQL: {error}")
finally:
    # Ensure the connection is closed
    if conn:
        cursor.close()
        conn.close()
        print("PostgreSQL connection closed.")

Summary

Task SQLite (sqlite3) PostgreSQL (psycopg2)
Connect sqlite3.connect('file.db') psycopg2.connect(...)
Placeholder %s
Insert One cursor.execute("...", (val1, val2)) cursor.execute("...", (val1, val2))
Insert Many cursor.executemany("...", list_of_tuples) cursor.executemany("...", list_of_tuples)
Commit conn.commit() conn.commit()
Close conn.close() conn.close()

The key takeaway is that Python acts as a client to a database. You use a specific library to translate your Python commands into the SQL language that the database understands.

分享:
扫描分享到社交APP
上一篇
下一篇