Ubuntu中Python数据库连接配置指南
在Ubuntu系统中配置Python与数据库的连接,需根据目标数据库类型(如MySQL、PostgreSQL、SQLite)完成环境准备→驱动安装→数据库配置→代码编写四大步骤。以下是具体操作流程:
Ubuntu系统通常预装Python 3,需确认版本并安装pip(Python包管理工具):
python3 --version # 检查Python 3版本
sudo apt update
sudo apt install python3 python3-pip # 安装/更新Python与pip
sudo apt update
sudo apt install mysql-server # 安装MySQL
sudo systemctl start mysql # 启动服务
sudo systemctl enable mysql # 设置开机自启
运行安全脚本设置root密码及基础安全选项:
sudo mysql_secure_installation
按提示操作(如设置root密码、移除匿名用户、禁止远程root登录等)。
登录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;
安装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
sudo apt update
sudo apt install postgresql postgresql-contrib # 安装PostgreSQL及扩展工具
sudo systemctl start postgresql
sudo systemctl enable 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
若需允许远程连接,需编辑pg_hba.conf(身份验证配置)和postgresql.conf(监听地址):
sudo nano /etc/postgresql/<version>/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/<version>/main/postgresql.conf
找到listen_addresses = 'localhost',确保其值为localhost(仅本地连接)或'*'(允许远程连接)。
重启服务使配置生效:
sudo systemctl restart postgresql
安装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
SQLite是轻量级文件型数据库,无需安装服务器,直接通过Python标准库sqlite3操作。
若未安装,运行:
sudo apt update
sudo apt install sqlite3 libsqlite3-dev
创建/连接数据库文件(如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-connector-python、PostgreSQL用psycopg2),避免兼容性问题。SELECT/INSERT/UPDATE/DELETE权限。try-except-finally块捕获连接/查询错误(如OperationalError、ProgrammingError),避免程序崩溃。os.getenv('DB_PASSWORD'))或配置文件(如.env)管理。cursor和connection,释放数据库资源(可使用with语句自动管理)。通过以上步骤,即可在Ubuntu系统中完成Python与常见数据库的连接配置。