Ubuntu中Python数据库连接配置指南
在Ubuntu系统中配置Python与数据库的连接,需根据目标数据库类型(如MySQL、PostgreSQL、SQLite)完成环境准备→驱动安装→数据库配置→代码编写四大步骤。以下是具体操作流程:
一、前置准备:安装Python与pip
Ubuntu系统通常预装Python 3,需确认版本并安装pip(Python包管理工具):
python3 --version # 检查Python 3版本
sudo apt update
sudo apt install python3 python3-pip # 安装/更新Python与pip
二、常见数据库配置步骤
1. MySQL数据库
(1)安装MySQL服务器
sudo apt update
sudo apt install mysql-server # 安装MySQL
sudo systemctl start mysql # 启动服务
sudo systemctl enable mysql # 设置开机自启
(2)配置MySQL安全设置
运行安全脚本设置root密码及基础安全选项:
sudo mysql_secure_installation
按提示操作(如设置root密码、移除匿名用户、禁止远程root登录等)。
(3)创建数据库与用户
登录MySQL控制台:
sudo mysql
执行以下SQL创建数据库(如mydb)和用户(如myuser,密码mypassword):
CREATE DATABASE mydb;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
(4)安装Python驱动并编写代码
安装MySQL连接器:
pip3 install mysql-connector-python # 或使用PyMySQL:pip3 install PyMySQL
编写Python连接代码(mysql_connect.py):
import mysql.connector
from mysql.connector import Error
try:
# 建立连接(替换为实际参数)
connection = mysql.connector.connect(
host='localhost',
user='myuser',
password='mypassword',
database='mydb'
)
if connection.is_connected():
print("Connected to MySQL Database version:", connection.get_server_info())
# 执行查询
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();")
record = cursor.fetchone()
print("Connected to database:", record)
except Error as e:
print("MySQL connection error:", e)
finally:
# 关闭连接
if 'connection' in locals() and connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection closed.")
运行脚本:
python3 mysql_connect.py
2. PostgreSQL数据库
(1)安装PostgreSQL服务器
sudo apt update
sudo apt install postgresql postgresql-contrib # 安装PostgreSQL及扩展工具
sudo systemctl start postgresql
sudo systemctl enable postgresql
(2)配置PostgreSQL用户与数据库
切换至postgres用户(默认超级用户)并进入psql控制台:
sudo -u postgres psql
执行以下SQL创建数据库(如mydb)和用户(如myuser,密码mypassword):
CREATE DATABASE mydb;
CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
\q # 退出psql
(3)修改PostgreSQL配置(可选)
若需允许远程连接,需编辑pg_hba.conf(身份验证配置)和postgresql.conf(监听地址):
sudo nano /etc/postgresql//main/pg_hba.conf
将host all all 127.0.0.1/32 peer修改为host all all 127.0.0.1/32 md5(允许本地MD5密码认证)。
编辑postgresql.conf:
sudo nano /etc/postgresql//main/postgresql.conf
找到listen_addresses = 'localhost',确保其值为localhost(仅本地连接)或'*'(允许远程连接)。
重启服务使配置生效:
sudo systemctl restart postgresql
(4)安装Python驱动并编写代码
安装PostgreSQL连接器:
pip3 install psycopg2-binary # 预编译版本(无需编译)
# 或 pip3 install psycopg2(需安装Python开发工具:sudo apt install python3-dev)
编写Python连接代码(postgresql_connect.py):
import psycopg2
from psycopg2 import OperationalError
try:
# 建立连接(替换为实际参数)
connection = psycopg2.connect(
dbname='mydb',
user='myuser',
password='mypassword',
host='localhost'
)
print("Connected to PostgreSQL Database")
# 执行查询
cursor = connection.cursor()
cursor.execute("SELECT version();")
db_version = cursor.fetchone()
print("PostgreSQL database version:", db_version)
except OperationalError as e:
print("PostgreSQL connection error:", e)
finally:
# 关闭连接
if 'connection' in locals():
cursor.close()
connection.close()
print("PostgreSQL connection closed.")
运行脚本:
python3 postgresql_connect.py
3. SQLite数据库(嵌入式,无需服务器)
SQLite是轻量级文件型数据库,无需安装服务器,直接通过Python标准库sqlite3操作。
(1)安装SQLite(可选)
若未安装,运行:
sudo apt update
sudo apt install sqlite3 libsqlite3-dev
(2)编写Python代码
创建/连接数据库文件(如mydb.db)并执行操作:
import sqlite3
# 连接数据库(若文件不存在则自动创建)
connection = sqlite3.connect('mydb.db')
cursor = connection.cursor()
# 创建表(若不存在)
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE)''')
# 插入数据
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'alice@example.com'))
connection.commit() # 提交事务(必做,否则数据不会保存)
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
cursor.close()
connection.close()
三、注意事项
- 驱动选择:优先使用官方推荐的驱动(如MySQL用
mysql-connector-python、PostgreSQL用psycopg2),避免兼容性问题。 - 权限配置:确保数据库用户拥有对应数据库的
SELECT/INSERT/UPDATE/DELETE权限。 - 异常处理:代码中需添加
try-except-finally块捕获连接/查询错误(如OperationalError、ProgrammingError),避免程序崩溃。 - 敏感信息保护:不要将数据库密码硬编码在代码中,建议使用环境变量(如
os.getenv('DB_PASSWORD'))或配置文件(如.env)管理。 - 连接关闭:操作完成后务必关闭
cursor和connection,释放数据库资源(可使用with语句自动管理)。
通过以上步骤,即可在Ubuntu系统中完成Python与常见数据库的连接配置。