在 Debian 上“连接 Python 数据库”通常分两步:
下面按常见数据库分别说明(以 Debian 11/12 为例)。
sudo apt update
sudo apt install mariadb-server -y
sudo systemctl enable --now mariadb
推荐 mysql-connector-python 或 PyMySQL:
pip install mysql-connector-python
# 或
pip install pymysql
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()
sudo apt install postgresql -y
sudo systemctl enable --now postgresql
pip install psycopg2
# 如编译失败可用
pip install psycopg2-binary
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()
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()
sudo apt install python3-pip
ufwbind-address)python3 -m venv venv
source venv/bin/activate
pip install xxx
如果你说的是 “Python 连哪个数据库” 或 “本地还是远程”,可以告诉我具体场景,我可以给你更精确的命令。