阅读量:2
在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和客户端库。以下是一些常见数据库的连接方法:
1. 连接MySQL数据库
安装MySQL客户端库
sudo apt update
sudo apt install python3-mysqldb
使用Python连接MySQL
import MySQLdb
# 连接数据库
conn = MySQLdb.connect(
host="localhost",
user="your_username",
passwd="your_password",
db="your_database"
)
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
2. 连接PostgreSQL数据库
安装PostgreSQL客户端库
sudo apt update
sudo apt install python3-psycopg2
使用Python连接PostgreSQL
import psycopg2
# 连接数据库
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="localhost",
port="5432"
)
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
3. 连接SQLite数据库
使用Python内置的sqlite3模块
import sqlite3
# 连接数据库
conn = sqlite3.connect('your_database.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
4. 连接MongoDB数据库
安装MongoDB客户端库
sudo apt update
sudo apt install python3-pymongo
使用Python连接MongoDB
from pymongo import MongoClient
# 连接数据库
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 查询文档
documents = collection.find()
for document in documents:
print(document)
# 关闭连接
client.close()
总结
以上是几种常见数据库在Ubuntu上使用Python连接的示例。根据你使用的数据库类型,选择相应的客户端库并进行安装,然后按照示例代码进行连接和操作即可。
以上就是关于“Ubuntu Python数据库连接怎么做”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm