在Ubuntu上配置Python连接数据库通常涉及以下几个步骤:
确保你的Ubuntu系统上已经安装了Python和pip(Python的包管理器)。你可以通过运行以下命令来安装Python和pip:
sudo apt update
sudo apt install python3 python3-pip
接下来,根据你想要连接的数据库类型,安装相应的Python驱动。例如:
MySQL: 使用 mysql-connector-python 或 PyMySQL。
pip3 install mysql-connector-python
# 或者
pip3 install PyMySQL
PostgreSQL: 使用 psycopg2。
pip3 install psycopg2
SQLite: Python标准库中已经包含了 sqlite3 模块,无需额外安装。
如果你还没有安装数据库服务器,需要先安装一个。例如:
MySQL:
sudo apt update
sudo apt install mysql-server
安装完成后,启动并启用MySQL服务:
sudo systemctl start mysql
sudo systemctl enable mysql
运行安全脚本以设置root密码和其他安全选项:
sudo mysql_secure_installation
PostgreSQL:
sudo apt update
sudo apt install postgresql postgresql-contrib
创建数据库和用户:
sudo -u postgres psql
在psql shell中:
CREATE DATABASE yourdatabase;
CREATE USER yourusername WITH ENCRYPTED PASSWORD 'yourpassword';
GRANT ALL PRIVILEGES ON DATABASE yourdatabase TO yourusername;
\q
使用Python编写代码来连接数据库。以下是一些示例代码:
import mysql.connector
# 连接到数据库
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 创建游标
cursor = cnx.cursor()
# 执行查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
for row in cursor:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
import psycopg2
# 连接到数据库
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="localhost"
)
# 创建游标
cur = conn.cursor()
# 执行查询
cur.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cur.close()
conn.close()
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
# 创建游标
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks (
id INTEGER PRIMARY KEY,
trans text,
symbol text,
qty real,
price real
)''')
# 插入数据
cursor.execute("INSERT INTO stocks (trans, symbol, qty, price) VALUES (?, ?, ?, ?)",
('BUY', 'AAPL', 100, 220.14))
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM stocks")
# 获取查询结果
for row in cursor:
print(row)
# 关闭连接
conn.close()
保存你的Python脚本(例如 connect_db.py),然后在终端中运行它:
python3 connect_db.py
如果一切正常,你应该能够看到从数据库表中检索到的记录。