在Ubuntu上配置Python连接数据库通常涉及以下几个步骤:
安装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代码连接数据库
使用Python编写代码来连接数据库。以下是一些示例代码:
MySQL 示例
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()
PostgreSQL 示例
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()
SQLite 示例
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脚本
保存你的Python脚本(例如 connect_db.py),然后在终端中运行它:
python3 connect_db.py
如果一切正常,你应该能够看到从数据库表中检索到的记录。
以上就是关于“Ubuntu上Python数据库连接怎样配置”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm