在 Debian 上用 Python 连接数据库,通常分三步:安装数据库和驱动 → 安装 Python 库 → 写代码连接。下面按常见数据库分别说明。
更新系统:
sudo apt update
sudo apt upgrade -y
安装 Python 和 pip:
sudo apt install python3 python3-pip -y
sudo apt install mariadb-server -y
sudo mysql_secure_installation
pip3 install pymysql
# 或
pip3 install mysql-connector-python
import pymysql
conn = pymysql.connect(
host='localhost',
user='root',
password='your_password',
database='testdb'
)
cur = conn.cursor()
cur.execute("SELECT VERSION()")
print(cur.fetchone())
cur.close()
conn.close()
sudo apt install postgresql postgresql-contrib -y
sudo -u postgres psql
pip3 install psycopg2
# 若编译失败,用二进制版:
pip3 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())
cur.close()
conn.close()
pip3 install dbapi2 # 通常内置
import sqlite3
conn = sqlite3.connect("test.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS user(id INTEGER, name TEXT)")
conn.commit()
conn.close()
sudo apt install redis-server -y
pip3 install redis
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
print(r.get('foo'))
systemctl status mysql
systemctl status postgresql
使用虚拟环境:
python3 -m venv venv
source venv/bin/activate
pip install pymysql
pip3 install sqlalchemy
如果你告诉我:
我可以给你更精确的示例。