温馨提示×

debian怎么连接python数据库

小樊
43
2026-09-26 09:02:19
栏目: 编程语言

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

  1. 安装数据库(或确认数据库已存在)
  2. 安装 Python 数据库驱动,并写代码连接

下面按常见数据库分别说明(以 Debian 11/12 为例)。


一、连接 MySQL / MariaDB

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

sudo apt update
sudo apt install mariadb-server -y
sudo systemctl enable --now mariadb

2. 安装 Python 驱动

推荐 mysql-connector-python 或 PyMySQL:

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

3. Python 连接示例

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="your_password",
    database="testdb"
)

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

conn.close()

二、连接 PostgreSQL

1. 安装 PostgreSQL

sudo apt install postgresql -y
sudo systemctl enable --now postgresql

2. 安装 Python 驱动

pip install psycopg2
# 如编译失败可用
pip install psycopg2-binary

3. Python 连接示例

import psycopg2

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

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

conn.close()

三、连接 SQLite(无需安装数据库)

Debian 自带,Python 标准库支持:

import sqlite3

conn = sqlite3.connect("test.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS t(id INTEGER)")
conn.commit()
conn.close()

四、常见问题

1. pip 不存在

sudo apt install python3-pip

2. 远程连接失败

  • 检查防火墙:ufw
  • 数据库配置允许远程(如 bind-address)
  • 用户授权正确

3. 建议使用虚拟环境

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

如果你说的是 “Python 连哪个数据库” 或 “本地还是远程”,可以告诉我具体场景,我可以给你更精确的命令。

0 踩