温馨提示×

ubuntu怎么连接python数据库

小樊
40
2026-09-13 11:44:27
栏目: 编程语言

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

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

下面按常见数据库给你说明。


一、连接 MySQL / MariaDB

1. 安装 MySQL(如未安装)

sudo apt update
sudo apt install mysql-server
sudo systemctl start mysql
sudo systemctl enable mysql

2. 安装 Python 驱动

推荐使用 pymysqlmysql-connector-python

pip install pymysql

3. Python 连接示例

import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='你的密码',
    database='test_db',
    charset='utf8mb4'
)

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

conn.close()

二、连接 PostgreSQL

1. 安装 PostgreSQL

sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql

2. 安装 Python 驱动

pip install psycopg2

3. Python 连接示例

import psycopg2

conn = psycopg2.connect(
    host="localhost",
    user="postgres",
    password="你的密码",
    dbname="test_db"
)

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

conn.close()

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

SQLite 是 Python 内置支持的。

import sqlite3

conn = sqlite3.connect("test.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY, name TEXT)")
conn.commit()
conn.close()

四、常见问题

1. 远程连接失败

  • 检查防火墙:sudo ufw allow 3306
  • 修改数据库配置,允许远程 IP
  • 确保用户有远程访问权限

2. pip 不存在

sudo apt install python3-pip

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

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

如果你能告诉我:

  • 用的是 哪种数据库(MySQL / PostgreSQL / SQLite / MongoDB)
  • 本地还是远程连接

我可以给你更精确的配置步骤。

0