温馨提示×

centos如何连接python数据库

小樊
45
2026-10-03 09:11:36
栏目: 编程语言

在 CentOS 上“连接 Python 数据库”通常分为 两步:

  1. CentOS 上安装并运行数据库(如 MySQL / PostgreSQL)
  2. 用 Python 连接该数据库(使用对应驱动)

下面以 MySQL 和 PostgreSQL 为例,讲最常见做法。


一、CentOS 上安装数据库(以 MySQL 为例)

1. 安装 MySQL

sudo yum install -y mariadb-server
# 或 MySQL(CentOS 8+)
sudo dnf install -y mysql-server

2. 启动数据库

sudo systemctl start mariadb
sudo systemctl enable mariadb

3. 初始化(首次)

sudo mysql_secure_installation

4. 创建数据库和用户

CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;

二、Python 连接数据库

方式一:连接 MySQL(推荐 pymysql)

1. 安装 Python 和 pip

sudo yum install -y python3 python3-pip

2. 安装驱动

pip3 install pymysql

3. Python 连接示例

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()

方式二:连接 PostgreSQL

1. 安装 PostgreSQL

sudo yum install -y postgresql-server
sudo postgresql-setup initdb
sudo systemctl start postgresql

2. 安装 Python 驱动

pip3 install psycopg2

3. Python 示例

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()

三、常见问题

1. 连接被拒绝

  • 数据库未启动
  • 用户只允许 localhost
  • 防火墙未放行端口(如 3306)

2. 远程连接

CREATE USER 'testuser'@'%' IDENTIFIED BY 'password';

并修改配置文件:

bind-address = 0.0.0.0

3. 使用虚拟环境(推荐)

python3 -m venv venv
source venv/bin/activate
pip install pymysql

四、总结

在 CentOS 上用 Python 连接数据库的核心是:

✅ 数据库服务正常运行
✅ 正确的用户和权限
✅ Python 安装对应数据库驱动
✅ 使用 host/user/password/db 正确连接

如果你指的是 SQLite / Redis / MongoDB / Oracle,可以告诉我具体数据库,我可以给你对应方案。

0 踩