杰瑞科技汇

Python 3.5如何连接MySQL?

Of course! Connecting MySQL to Python 3.5 requires a specific approach, as the most popular library, mysql-connector-python, has dropped support for Python 3.5 in recent versions.

Python 3.5如何连接MySQL?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the recommended library, installation, and code examples for Python 3.5.

The Best Library for Python 3.5: mysqlclient

While mysql-connector-python is the official driver from Oracle, its versions from 8.0.23 onwards no longer support Python 3.5.

The best and most robust alternative is mysqlclient. It's a fork of the classic MySQLdb library, which was the standard for Python 2. It's fully compatible with Python 3 and is what the very popular Django ORM uses by default. It's fast and stable.


Step 1: Prerequisites (Important!)

mysqlclient is a C extension, which means it requires some system-level dependencies to be installed before you can install it via pip.

Python 3.5如何连接MySQL?-图2
(图片来源网络,侵删)

On Debian / Ubuntu:

You'll need the python3.5-dev and libmysqlclient-dev packages.

sudo apt-get update
sudo apt-get install python3.5-dev libmysqlclient-dev

On macOS (using Homebrew):

You'll need the mysql-client package.

brew install mysql-client

You might also need to link it:

brew link mysql-client

On Windows:

This is the trickiest. The easiest way is to use a pre-compiled binary. Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages is a great resource.

  1. Go to: https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
  2. Download the file corresponding to your Python version and architecture. For Python 3. 64-bit, it will be named something like mysqlclient‑1.4.6‑cp35‑cp35m‑win_amd64.whl.
  3. Install the downloaded .whl file using pip. Open a command prompt and navigate to your Downloads folder, then run:
    pip install mysqlclient‑1.4.6‑cp35‑cp35m‑win_amd64.whl

Step 2: Install the Library

Once your system dependencies are in place, you can install mysqlclient using pip. It's highly recommended to use pip3 to ensure you're installing it for your Python 3.5 environment.

pip3 install mysqlclient

If this command succeeds, you're ready to write Python code!


Step 3: Python 3.5 Code Examples

Here are the essential operations: connecting, querying (select), inserting data, and closing the connection.

Basic Connection and a Simple Query

This example connects to your MySQL server, executes a SELECT query, and prints the results.

import MySQLdb
# --- Database Connection Details ---
# Replace with your own database details
db_host = "localhost"
db_user = "your_username"
db_pass = "your_password"
db_name = "your_database_name"
try:
    # Establish a connection to the database
    # For Python 3.5, you use the connection object directly, not a cursor factory
    conn = MySQLdb.connect(
        host=db_host,
        user=db_user,
        passwd=db_pass,
        db=db_name
    )
    # Create a cursor object. A cursor is used to execute SQL commands.
    cursor = conn.cursor()
    # --- Example 1: SELECT Query ---
    print("Executing SELECT query...")
    sql_query = "SELECT id, name, email FROM users;"
    cursor.execute(sql_query)
    # Fetch all the records
    results = cursor.fetchall()
    print(f"Found {cursor.rowcount} records.")
    print("-" * 30)
    for row in results:
        # row is a tuple, e.g., (1, 'Alice', 'alice@example.com')
        user_id, name, email = row
        print(f"ID: {user_id}, Name: {name}, Email: {email}")
except MySQLdb.Error as e:
    # Handle potential errors
    print(f"Error connecting to MySQL or executing query: {e}")
finally:
    # Ensure the connection is closed
    if 'conn' in locals() and conn.open:
        cursor.close()
        conn.close()
        print("\nMySQL connection is closed.")

Inserting Data with Parameters (Prevents SQL Injection)

Never use string formatting ( or f-strings) to insert variables directly into a query. This is a major security risk called SQL Injection. Always use parameterized queries.

import MySQLdb
# --- Database Connection Details ---
db_host = "localhost"
db_user = "your_username"
db_pass = "your_password"
db_name = "your_database_name"
try:
    conn = MySQLdb.connect(
        host=db_host,
        user=db_user,
        passwd=db_pass,
        db=db_name
    )
    cursor = conn.cursor()
    # --- Example 2: INSERT Query with Parameters ---
    new_name = "Bob"
    new_email = "bob@example.com"
    # The query uses %s as a placeholder. MySQLdb will sanitize the input.
    # Note: Even for numbers, you use %s.
    sql_insert = "INSERT INTO users (name, email) VALUES (%s, %s);"
    # Create a tuple with the data to be inserted
    data_to_insert = (new_name, new_email)
    print(f"Executing INSERT query for user: {new_name}")
    cursor.execute(sql_insert, data_to_insert)
    # Commit the transaction to save the changes to the database
    conn.commit()
    print(f"Successfully inserted record with ID: {cursor.lastrowid}")
except MySQLdb.Error as e:
    # If an error occurs, roll back any changes
    if 'conn' in locals() and conn.open:
        conn.rollback()
    print(f"Error inserting data: {e}")
finally:
    if 'conn' in locals() and conn.open:
        cursor.close()
        conn.close()
        print("\nMySQL connection is closed.")

Important: The Python 3.5 Context Manager with

In modern Python (3.10+), mysql-connector-python supports the with statement for automatic connection closing. However, mysqlclient for Python 3.5 does not natively support this. The with statement will raise a TypeError because the connection object is not a "context manager".

You must manually ensure your connections are closed using a try...finally block, as shown in the examples above. This is the standard and safe way to handle resources in Python 3.5.

Summary

Task Recommended Action for Python 3.5
Library Use mysqlclient.
Installation pip3 install mysqlclient (after installing system dependencies).
Connecting MySQLdb.connect(host=..., user=..., passwd=..., db=...)
Cursor conn.cursor()
Executing cursor.execute("YOUR SQL QUERY", (param1, param2))
Fetching cursor.fetchone(), cursor.fetchmany(size), or cursor.fetchall()
Committing conn.commit() (after INSERT, UPDATE, DELETE)
Rolling Back conn.rollback() (on error)
Closing Always use cursor.close() and conn.close() in a finally block.
分享:
扫描分享到社交APP
上一篇
下一篇