温馨提示×

centos怎样连接python数据库

小樊
33
2026-10-09 06:18:11
栏目: 编程语言

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

  1. 安装数据库(或确保数据库可访问)
  2. 在 Python 中使用对应驱动/库连接数据库

下面以 常见数据库 为例说明(以 CentOS 7 / 8 通用)。


一、连接 MySQL / MariaDB

1. 安装数据库(如本地需要)

# CentOS 7
yum install -y mariadb-server
systemctl start mariadb
systemctl enable mariadb

# CentOS 8
dnf install -y mariadb-server
systemctl start mariadb

2. 安装 Python 连接库

pip3 install pymysql
# 或
pip3 install mysql-connector-python

3. Python 连接示例

import pymysql

conn = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='password',
    database='testdb',
    charset='utf8mb4'
)

cur = conn.cursor()
cur.execute("SELECT VERSION()")
print(cur.fetchone())

cur.close()
conn.close()

二、连接 PostgreSQL

1. 安装 PostgreSQL

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

2. 安装 Python 库

pip3 install psycopg2
# 若编译失败
pip3 install psycopg2-binary

3. Python 示例

import psycopg2

conn = psycopg2.connect(
    host="127.0.0.1",
    user="postgres",
    password="password",
    dbname="testdb"
)

cur = conn.cursor()
cur.execute("SELECT version()")
print(cur.fetchone())

cur.close()
conn.close()

三、连接 SQLite(无需服务)

pip3 install sqlite3   # 一般自带
import sqlite3

conn = sqlite3.connect("test.db")
cur = conn.cursor()
cur.execute("SELECT sqlite_version()")
print(cur.fetchone())

四、连接 Redis(非关系型)

pip3 install redis
import redis

r = redis.Redis(host='127.0.0.1', port=6379, db=0)
r.set('name', 'centos')
print(r.get('name'))

五、常见问题排查

1. 无法连接数据库

  • 防火墙
firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --reload
  • 数据库允许远程
  • 用户权限

2. pip 不存在

yum install -y python3-pip

3. 缺少依赖

yum install -y gcc python3-devel

六、如果你指的是“Python 操作数据库”

请告诉我:

  • 用的是 哪种数据库(MySQL / PostgreSQL / Oracle / SQL Server)
  • 是否 本地或远程
  • CentOS 版本

我可以直接给你完整可运行代码。

0 踩