杰瑞科技汇

Centos下Python如何连接MySQL?

Of course! Here is a comprehensive guide covering the installation and usage of Python and MySQL on a CentOS system. This guide is broken down into sections to help you find what you need quickly.

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

Overview

This guide will cover:

  1. System Preparation: Ensuring your CentOS system is ready for installations.
  2. Installing Python: The modern and recommended way to install Python on CentOS.
  3. Installing MySQL: Installing the official MySQL community server.
  4. Connecting Python to MySQL: The crucial step of making them talk to each other using a library.
  5. A Complete Example: A full Python script to perform CRUD (Create, Read, Update, Delete) operations.
  6. Best Practices: Security and deployment tips.

Section 1: System Preparation

Before installing any software, it's always a good practice to update your system's package database and upgrade existing packages.

Open a terminal and run the following commands:

# Update the package database
sudo dnf update -y
# Upgrade all installed packages to their latest versions
sudo dnf upgrade -y

Note: CentOS 8 and newer use dnf as the package manager. If you are on an older version of CentOS 7, you would use yum instead of dnf in all the following commands.

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

Section 2: Installing Python

CentOS comes with Python 3.6 pre-installed on CentOS 7 and Python 3.6/3.8 on CentOS 8/9. However, it's often better to use a more recent version managed by dnf or scl (Software Collections) to avoid conflicts with the system's Python.

Option A: Using DNF (Recommended for CentOS 8/9)

This is the simplest method for modern CentOS versions.

# Install the Python 3 package and its development tools
sudo dnf install python3 python3-devel python3-pip -y

Verify the installation:

python3 --version
# Expected output: Python 3.x.x
pip3 --version
# Expected output: pip x.x.x from ...

Option B: Using Software Collections (SCL) (Recommended for CentOS 7)

SCL allows you to install multiple versions of Python side-by-side without overwriting the system's default Python.

Centos下Python如何连接MySQL?-图3
(图片来源网络,侵删)
# Install the SCL repository for Python 3.9 (or another version)
sudo dnf install centos-release-scl -y
# Install the Python 3.9 collection and its tools
sudo dnf install rh-python39 rh-python39-python-devel rh-python39-python-pip -y

To use this specific Python version, you need to enable it in your terminal session:

scl enable rh-python39 bash

Your command prompt will change, indicating the SCL environment is active. You can now use python and pip directly.


Section 3: Installing MySQL

We will install the official MySQL Community Server, which is more up-to-date than the default mariadb package in CentOS repositories.

Step 1: Add the Official MySQL Repository

sudo dnf localinstall https://dev.mysql.com/get/mysql80-community-release-el7-9.noarch.rpm -y

Note: The URL above is for CentOS 7. For CentOS 8, use ...el8-... and for CentOS 9, use ...el9-.... Check the MySQL Yum Repository page for the latest links.

Step 2: Verify the Repository

It's good practice to check that the correct repository is enabled.

sudo dnf repolist enabled | "^\s*mysql.*-.*-.*\s*$" | grep ".*" | awk '{print $3}'

You should see output like mysql80-community/x86_64 and mysql80-community-source/....

Step 3: Install the MySQL Server

sudo dnf install mysql-community-server -y

Step 4: Start and Enable MySQL

# Start the MySQL service
sudo systemctl start mysqld
# Enable the service to start automatically on boot
sudo systemctl enable mysqld

Step 5: Secure the Installation

Run the security script to set a root password, remove anonymous users, disallow remote root login, and remove test databases.

sudo mysql_secure_installation

You will be prompted through a series of questions. It is highly recommended to answer Y (yes) to all of them.


Section 4: Connecting Python to MySQL (The Library)

Python cannot talk to MySQL directly. You need a "driver" or "library". The most popular and recommended one is mysql-connector-python.

Install the Library

Use pip3 to install it. If you used SCL, make sure you are in the correct environment (scl enable rh-python39 bash).

pip3 install mysql-connector-python

Verify the Installation

python3 -c "import mysql.connector; print('MySQL Connector is installed successfully!')"
# Expected output: MySQL Connector is installed successfully!

Section 5: A Complete Python Example

Let's put everything together. This example will connect to your MySQL database, create a table, insert data, query it, update a record, and delete it.

Prerequisites:

  1. MySQL is installed and running.
  2. You have completed mysql_secure_installation.
  3. You have created a MySQL user and database for this example.

First, log into MySQL to set up the database and user:

# Log in as root (or another privileged user)
sudo mysql -u root -p
# Inside the MySQL shell:
CREATE DATABASE myapp_db;
CREATE USER 'myapp_user'@'localhost' IDENTIFIED BY 'a_strong_password';
GRANT ALL PRIVILEGES ON myapp_db.* TO 'myapp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Now, create a Python script named app.py:

import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password, db_name=None):
    """Create a database connection to a MySQL server."""
    connection = None
    try:
        if db_name:
            connection = mysql.connector.connect(
                host=host_name,
                user=user_name,
                passwd=user_password,
                database=db_name
            )
        else:
            connection = mysql.connector.connect(
                host=host_name,
                user=user_name,
                passwd=user_password
            )
        print("Connection to MySQL successful" if db_name else "Connection to MySQL server successful")
    except Error as e:
        print(f"The error '{e}' occurred")
    return connection
def create_database(connection, query):
    """Create a database from a query."""
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        print("Database created successfully")
    except Error as e:
        print(f"The error '{e}' occurred")
def execute_query(connection, query, data=None):
    """Execute a single query with optional data."""
    cursor = connection.cursor()
    try:
        if data:
            cursor.execute(query, data)
        else:
            cursor.execute(query)
        connection.commit()
        print("Query executed successfully")
    except Error as e:
        print(f"The error '{e}' occurred")
def execute_read_query(connection, query):
    """Execute a read query and return the results."""
    cursor = connection.cursor(dictionary=True) # dictionary=True makes results easy to use
    result = None
    try:
        cursor.execute(query)
        result = cursor.fetchall()
        return result
    except Error as e:
        print(f"The error '{e}' occurred")
        return result
# --- Main Execution ---
# 1. Create the database connection (without specifying a database initially)
# Replace with your actual MySQL root credentials
connection = create_connection("localhost", "root", "YOUR_ROOT_PASSWORD")
# 2. Create the database (if it doesn't exist)
create_database_query = "CREATE DATABASE IF NOT EXISTS myapp_db"
create_database(connection, create_database_query)
# 3. Close the initial connection and reconnect to the specific database
if connection.is_connected():
    connection.close()
connection = create_connection("localhost", "root", "YOUR_ROOT_PASSWORD", "myapp_db")
# 4. Create a table
create_users_table_query = """
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name TEXT NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    age INT
)
"""
execute_query(connection, create_users_table_query)
# 5. Insert data into the table
insert_user_query = "INSERT INTO users (name, email, age) VALUES (%s, %s, %s)"
# Use a tuple for the data
user_data = ("John Doe", "john.doe@example.com", 30)
execute_query(connection, insert_user_query, user_data)
# 6. Select data from the table
select_users_query = "SELECT * FROM users"
users = execute_read_query(connection, select_users_query)
for user in users:
    print(user)
# Expected output: {'id': 1, 'name': 'John Doe', 'email': 'john.doe@example.com', 'age': 30}
# 7. Update a user's age
update_user_query = "UPDATE users SET age = %s WHERE name = %s"
update_data = (31, "John Doe")
execute_query(connection, update_user_query, update_data)
# 8. Select data again to see the update
users = execute_read_query(connection, select_users_query)
for user in users:
    print(user)
# Expected output: {'id': 1, 'name': 'John Doe', 'email': 'john.doe@example.com', 'age': 31}
# 9. Delete a user
delete_user_query = "DELETE FROM users WHERE name = %s"
delete_data = ("John Doe",)
execute_query(connection, delete_user_query, delete_data)
# 10. Verify deletion
users = execute_read_query(connection, select_users_query)
print("Users after deletion:", users)
# Expected output: Users after deletion: []
# Close the connection
if connection.is_connected():
    connection.close()
    print("MySQL connection is closed")

Section 6: Best Practices & Troubleshooting

Security

  • Never hardcode credentials in your scripts. Use environment variables or a configuration file with restricted permissions.
  • Principle of Least Privilege: The Python application should use a dedicated MySQL user (myapp_user) with only the permissions it needs (e.g., SELECT, INSERT, UPDATE, DELETE on myapp_db), not root.
  • Use connection pooling in production applications for better performance and resource management.

Troubleshooting

  • mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES)

  • mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost' (111 "Connection refused")

    • Cause: The MySQL service is not running.
    • Solution: Start the service with sudo systemctl start mysqld.
  • ModuleNotFoundError: No module named 'mysql'

    • Cause: The mysql-connector-python library is not installed or not in the Python path.
    • Solution: Ensure you installed it with pip3 install mysql-connector-python and that you are running the script with the correct Python interpreter (e.g., python3 app.py). If you used SCL, make sure you are in the correct shell environment.
分享:
扫描分享到社交APP
上一篇
下一篇