在 CentOS 上“连接 Python 数据库”通常分为 两步:
下面以 MySQL 和 PostgreSQL 为例,讲最常见做法。
sudo yum install -y mariadb-server
# 或 MySQL(CentOS 8+)
sudo dnf install -y mysql-server
sudo systemctl start mariadb
sudo systemctl enable mariadb
sudo mysql_secure_installation
CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;
sudo yum install -y python3 python3-pip
pip3 install pymysql
import pymysql
conn = pymysql.connect(
host='localhost',
user='testuser',
password='password',
database='testdb',
charset='utf8mb4'
)
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
print(cursor.fetchone())
conn.close()
sudo yum install -y postgresql-server
sudo postgresql-setup initdb
sudo systemctl start postgresql
pip3 install psycopg2
import psycopg2
conn = psycopg2.connect(
host="localhost",
user="postgres",
password="yourpassword",
dbname="testdb"
)
cur = conn.cursor()
cur.execute("SELECT version()")
print(cur.fetchone())
conn.close()
localhostCREATE USER 'testuser'@'%' IDENTIFIED BY 'password';
并修改配置文件:
bind-address = 0.0.0.0
python3 -m venv venv
source venv/bin/activate
pip install pymysql
在 CentOS 上用 Python 连接数据库的核心是:
✅ 数据库服务正常运行
✅ 正确的用户和权限
✅ Python 安装对应数据库驱动
✅ 使用 host/user/password/db 正确连接
如果你指的是 SQLite / Redis / MongoDB / Oracle,可以告诉我具体数据库,我可以给你对应方案。