杰瑞科技汇

Linux下如何安装mysql-python?

Of course! Here's a comprehensive guide to using MySQL with Python on Linux, covering everything from installation to best practices.

Linux下如何安装mysql-python?-图1
(图片来源网络,侵删)

The Short Answer (TL;DR)

To connect a Python script to a MySQL database on Linux, you need to:

  1. Install the MySQL Server on your Linux machine.
  2. Install the Python MySQL driver. The most common one is mysql-connector-python.
  3. Write Python code to import the driver, establish a connection, execute queries, and process the results.

Step 1: Install MySQL Server on Linux

If you don't already have a MySQL server running, you need to install it.

For Debian / Ubuntu

# Update your package list
sudo apt update
# Install the MySQL server package
sudo apt install mysql-server
# Secure the installation (recommended)
# This will prompt you to set a root password, remove anonymous users, etc.
sudo mysql_secure_installation

For CentOS / RHEL / Fedora

# Install the MySQL server package
sudo dnf install mysql-server
# Enable and start the MySQL service
sudo systemctl enable --now mysqld
# Secure the installation (recommended)
sudo mysql_secure_installation

After installation, you can verify it's running with: sudo systemctl status mysql (or mysqld on some systems).


Step 2: Install the Python MySQL Driver

The Python standard library does not include a MySQL driver. You need to install one from the Python Package Index (PyPI). The officially recommended driver from Oracle is mysql-connector-python.

Linux下如何安装mysql-python?-图2
(图片来源网络,侵删)

Open your terminal and use pip to install it.

# It's good practice to use pip3 to ensure you're installing for Python 3
pip3 install mysql-connector-python

Alternative Drivers:

  • PyMySQL: Another very popular and lightweight pure-Python implementation.
    pip3 install PyMySQL
  • mysqlclient: A fork of the old MySQLdb library, which is a wrapper around the native C library libmysqlclient. It's very fast but can be trickier to install because it requires development headers.

For most use cases, mysql-connector-python is the best place to start due to its official support and ease of installation.


Step 3: Python Code Examples

Let's assume you have a MySQL database set up like this:

Linux下如何安装mysql-python?-图3
(图片来源网络,侵删)
  • Host: localhost (or 0.0.1)
  • Database Name: mytestdb
  • User: myuser
  • Password: mypassword

You can create this and a test table with the following SQL commands (run them from the MySQL shell):

-- Log in to the MySQL server
mysql -u root -p
-- Create a new database
CREATE DATABASE mytestdb;
-- Create a new user and grant privileges
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mytestdb.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
-- Switch to the new database
USE mytestdb;
-- Create a sample table
CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    position VARCHAR(50),
    salary DECIMAL(10, 2)
);
-- Insert some sample data
INSERT INTO employees (name, position, salary) VALUES
('Alice', 'Software Engineer', 90000.00),
('Bob', 'Project Manager', 105000.50),
('Charlie', 'Data Analyst', 75000.00);

Example 1: Basic Connection and Query (mysql-connector-python)

This script connects to the database, fetches all employees, and prints them.

# connect_mysql.py
import mysql.connector
from mysql.connector import Error
def get_db_connection():
    """Establishes a connection to the MySQL database."""
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='mytestdb',
            user='myuser',
            password='mypassword'
        )
        if connection.is_connected():
            print("Successfully connected to the database")
            return connection
    except Error as e:
        print(f"Error while connecting to MySQL: {e}")
        return None
def fetch_all_employees(connection):
    """Fetches and prints all records from the employees table."""
    try:
        cursor = connection.cursor(dictionary=True) # dictionary=True makes results easy to use
        sql_query = "SELECT id, name, position, salary FROM employees"
        cursor.execute(sql_query)
        records = cursor.fetchall()
        print("\n--- Employee Records ---")
        for row in records:
            print(f"ID: {row['id']}, Name: {row['name']}, Position: {row['position']}, Salary: ${row['salary']}")
    except Error as e:
        print(f"Error while fetching data: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            print("\nMySQL cursor is closed.")
if __name__ == "__main__":
    db_connection = get_db_connection()
    if db_connection:
        fetch_all_employees(db_connection)
        db_connection.close() # Don't forget to close the connection
        print("MySQL connection is closed.")

To run the script: python3 connect_mysql.py

Example 2: Inserting Data with Parameters (Prevents SQL Injection)

This is a critical best practice. Never format user input directly into a query string.

# insert_employee.py
import mysql.connector
from mysql.connector import Error
def insert_employee(connection, name, position, salary):
    """Inserts a new employee record into the database."""
    try:
        cursor = connection.cursor()
        # Use placeholders (%s) for user input. The driver will sanitize it.
        sql_query = "INSERT INTO employees (name, position, salary) VALUES (%s, %s, %s)"
        employee_data = (name, position, salary)
        cursor.execute(sql_query, employee_data)
        connection.commit() # Commit the transaction to save the changes
        print(f"Successfully inserted employee: {name}")
        print(f"Last inserted ID: {cursor.lastrowid}")
    except Error as e:
        print(f"Error while inserting data: {e}")
        connection.rollback() # Rollback in case of error
    finally:
        if connection.is_connected():
            cursor.close()
if __name__ == "__main__":
    db_connection = mysql.connector.connect(
        host='localhost',
        database='mytestdb',
        user='myuser',
        password='mypassword'
    )
    if db_connection.is_connected():
        # Example of inserting a new employee
        insert_employee(db_connection, 'David', 'DevOps Engineer', 110000.00)
        db_connection.close()
        print("MySQL connection is closed.")

Step 4: Best Practices

  1. Use Context Managers (with statement): This ensures that your database cursor and connection are automatically closed, even if errors occur. It's the recommended way to handle resources.

    import mysql.connector
    try:
        with mysql.connector.connect(
            host='localhost',
            database='mytestdb',
            user='myuser',
            password='mypassword'
        ) as connection:
            with connection.cursor(dictionary=True) as cursor:
                cursor.execute("SELECT * FROM employees")
                for row in cursor:
                    print(row)
    except Error as e:
        print(f"Error: {e}")
    # The 'with' block automatically closes the cursor and connection here
  2. Always Parameterize Queries: As shown in Example 2, use %s placeholders and pass data as a tuple to cursor.execute(). This is the single most important defense against SQL Injection attacks.

  3. Manage Connections Efficiently: For applications (like web servers), opening and closing a database connection for every request is very slow. Use a connection pool. mysql-connector-python has a built-in pooling mechanism.

    from mysql.connector import pooling
    dbconfig = {
        "host": "localhost",
        "user": "myuser",
        "password": "mypassword",
        "database": "mytestdb"
    }
    # Create a connection pool
    connection_pool = pooling.MySQLConnectionPool(pool_name="mypool", pool_size=5, **dbconfig)
    # Get a connection from the pool
    connection = connection_pool.get_connection()
    # ... use the connection ...
    connection.close() # Returns the connection to the pool
  4. Handle Exceptions: Wrap your database logic in try...except Error as e: blocks to catch potential issues like lost connections, wrong credentials, or syntax errors in your SQL.

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