阅读量:0
在Ubuntu上配置Python数据库连接,首先需要确定你想要连接的数据库类型(例如MySQL、PostgreSQL、SQLite等)。以下是针对几种常见数据库的配置步骤:
1. MySQL
安装MySQL服务器
sudo apt update
sudo apt install mysql-server
安装Python的MySQL驱动
pip install mysql-connector-python
示例代码
import mysql.connector
# 连接到数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")
# 获取查询结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
2. PostgreSQL
安装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的PostgreSQL驱动
pip install psycopg2-binary
示例代码
import psycopg2
# 连接到数据库
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# 创建游标对象
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT * FROM yourtable")
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
3. SQLite
SQLite是一个嵌入式数据库,不需要单独安装服务器。
安装Python的SQLite驱动
pip install pysqlite3
示例代码
import sqlite3
# 连接到数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS yourtable (id INTEGER PRIMARY KEY, name TEXT)''')
# 插入数据
cursor.execute("INSERT INTO yourtable (name) VALUES ('Alice')")
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM yourtable")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
总结
- 确定数据库类型:根据需求选择合适的数据库。
- 安装数据库服务器:使用
apt包管理器安装相应的数据库服务器。 - 创建数据库和用户:配置数据库和用户权限。
- 安装Python驱动:使用
pip安装相应的Python数据库驱动。 - 编写连接代码:根据所选数据库类型编写连接和操作数据库的Python代码。
通过以上步骤,你可以在Ubuntu上成功配置Python数据库连接。
以上就是关于“Ubuntu上Python数据库连接怎么配置”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm