杰瑞科技汇

Python 3.5如何用MySQL?

Of course! Here is a comprehensive guide to using MySQL with Python 3.5.

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

The most important thing to understand is that the original MySQL driver for Python, MySQL-python, does not support Python 3. It is a legacy library for Python 2.

For Python 3.5, you have two excellent, modern, and actively maintained choices. The most recommended one is mysql-connector-python.


Option 1: The Recommended Choice - mysql-connector-python (Official Oracle Driver)

This is the official MySQL driver from Oracle. It's reliable, well-documented, and has excellent support for Python 3.

Installation

First, you need to install the library using pip. It's highly recommended to use a virtual environment to keep your project dependencies separate.

Python 3.5如何用MySQL?-图2
(图片来源网络,侵删)
# It's good practice to create a virtual environment first
# python3 -m venv my_project_env
# source my_project_env/bin/activate
# Install the driver
pip install mysql-connector-python

Basic Connection and Usage

Here is a complete, commented example of how to connect to a MySQL database, execute a query, and fetch the results.

Prerequisites:

  • You have a MySQL server running.
  • You have a database, a user, and a password for that database.
# import the MySQL Connector Python module
import mysql.connector
from mysql.connector import Error
def connect_to_mysql():
    """ Connect to MySQL database """
    conn = None
    try:
        # Establish the connection
        # Replace with your actual database details
        conn = mysql.connector.connect(
            host='localhost',          # Your MySQL server host
            database='your_database',  # Your database name
            user='your_username',      # Your database username
            password='your_password'   # Your database password
        )
        if conn.is_connected():
            db_info = conn.get_server_info()
            print(f"Successfully connected to MySQL Server version {db_info}")
            cursor = conn.cursor()
            cursor.execute("SELECT database();")
            record = cursor.fetchone()
            print(f"You're connected to database: {record[0]}")
    except Error as e:
        # Handle errors
        print(f"Error while connecting to MySQL: {e}")
    finally:
        # Close the connection in the 'finally' block to ensure it's always closed
        if conn and conn.is_connected():
            cursor.close()
            conn.close()
            print("MySQL connection is closed.")
# Run the function
connect_to_mysql()

Performing CRUD (Create, Read, Update, Delete) Operations

Let's build on the previous example to perform common database operations.

import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password, db_name):
    """ Create a database connection to the MySQL database """
    conn = None
    try:
        conn = mysql.connector.connect(
            host=host_name,
            user=user_name,
            passwd=user_password,
            database=db_name
        )
        print("Connection to MySQL DB successful")
    except Error as e:
        print(f"The error '{e}' occurred")
    return conn
# --- Let's assume our DB is called 'pydb' and has a 'users' table ---
# CREATE TABLE users (
#     id INT AUTO_INCREMENT PRIMARY KEY,
#     name VARCHAR(255) NOT NULL,
#     email VARCHAR(255) NOT NULL UNIQUE,
#     join_date DATE
# );
def create_user(conn, user):
    """ Create a new user in the users table """
    sql = ''' INSERT INTO users(name, email, join_date)
              VALUES(%s, %s, %s) '''
    try:
        cursor = conn.cursor()
        cursor.execute(sql, user)
        conn.commit() # IMPORTANT: Commit the transaction
        print("New user created successfully")
    except Error as e:
        print(f"The error '{e}' occurred")
def select_all_users(conn):
    """ Query all rows in the users table """
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users")
        rows = cursor.fetchall()
        for row in rows:
            print(row)
    except Error as e:
        print(f"The error '{e}' occurred")
def update_user_email(conn, user_id, new_email):
    """ Update email of a user """
    sql = ''' UPDATE users
              SET email = %s
              WHERE id = %s '''
    try:
        cursor = conn.cursor()
        cursor.execute(sql, (new_email, user_id))
        conn.commit()
        print(f"User {user_id}'s email updated successfully")
    except Error as e:
        print(f"The error '{e}' occurred")
def delete_user(conn, user_id):
    """ Delete a user by id """
    sql = "DELETE FROM users WHERE id = %s"
    try:
        cursor = conn.cursor()
        cursor.execute(sql, (user_id,))
        conn.commit()
        print(f"User {user_id} deleted successfully")
    except Error as e:
        print(f"The error '{e}' occurred")
# --- Main execution ---
if __name__ == '__main__':
    # Replace with your credentials
    connection = create_connection("localhost", "your_username", "your_password", "pydb")
    if connection:
        # Create
        new_user = ('Alice', 'alice@example.com', '2025-10-27')
        create_user(connection, new_user)
        new_user_2 = ('Bob', 'bob@example.com', '2025-10-27')
        create_user(connection, new_user_2)
        # Read
        print("\n--- All Users ---")
        select_all_users(connection)
        # Update
        print("\n--- Updating Bob's email ---")
        update_user_email(connection, 2, 'bob.smith@example.com')
        print("\n--- All Users After Update ---")
        select_all_users(connection)
        # Delete
        print("\n--- Deleting Alice ---")
        delete_user(connection, 1)
        print("\n--- All Users After Deletion ---")
        select_all_users(connection)
        connection.close()

Option 2: The High-Performance Choice - PyMySQL

PyMySQL is another very popular and pure-Python MySQL client. It's known for being lightweight and fast. It's also a great choice for Python 3.5.

Installation

# Install the driver
pip install PyMySQL

Basic Connection and Usage

The syntax is very similar to mysql-connector-python.

import pymysql
from pymysql import MySQLError
def connect_to_mysql_pymysql():
    """ Connect to MySQL database using PyMySQL """
    conn = None
    try:
        conn = pymysql.connect(
            host='localhost',
            user='your_username',
            password='your_password',
            database='your_database',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor # This returns rows as dictionaries
        )
        print("Successfully connected to MySQL using PyMySQL")
        with conn.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `name` FROM `users` WHERE `email` = %s"
            cursor.execute(sql, ('bob.smith@example.com',))
            result = cursor.fetchone()
            print(f"Found user: {result}")
    except MySQLError as e:
        print(f"Error while connecting to MySQL: {e}")
    finally:
        if conn:
            conn.close()
            print("MySQL connection is closed.")
# Run the function
connect_to_mysql_pymysql()

Comparison: mysql-connector-python vs. PyMySQL

Feature mysql-connector-python (Oracle) PyMySQL (Community)
Maintainer Oracle (Official) Community
Dependencies Requires C/C++ compilation (binary wheels provided). Pure Python, no external dependencies.
Features Very feature-rich (SSL, connection pooling, etc.). Core features are excellent. Some advanced features might be added later.
Ease of Use Very straightforward, standard Python DB-API 2.0. Also straightforward, standard Python DB-API 2.0.
Recommendation Best for most use cases, especially in production environments where official support is a plus. Excellent choice, especially if you prefer pure Python libraries or have issues with binary dependencies.

Handling Potential Issues in Python 3.5

  1. mysql-python is not supported: If you try pip install MySQL-python, it will fail or install a version that is incompatible with Python 3. Do not use this.
  2. pymysql vs mysqlclient: You might see mysqlclient recommended. It's a fork of the old MySQL-python that has been updated for Python 3. It's a high-performance C extension. However, for a beginner or for a standard Python 3.5 environment, mysql-connector-python or PyMySQL are simpler to install and manage as they don't require a C compiler.

Conclusion and Final Recommendation

For Python 3.5, start with mysql-connector-python. It is the official driver, well-supported, and its API is very intuitive for beginners.

Your workflow should be:

  1. Install: pip install mysql-connector-python
  2. Connect: Use mysql.connector.connect() with your credentials.
  3. Interact: Create a cursor, execute queries (cursor.execute()), and fetch data (cursor.fetchall(), cursor.fetchone(), cursor.fetchone()).
  4. Commit: For any INSERT, UPDATE, or DELETE, you must call connection.commit() to save the changes.
  5. Close: Always close your connection in a finally block to prevent resource leaks.
分享:
扫描分享到社交APP
上一篇
下一篇