阅读量:2
在Ubuntu上使用Python连接数据库,通常需要使用数据库的官方驱动或第三方库。以下是一些常见数据库的连接方法:
1. MySQL
安装MySQL客户端库:
sudo apt-get update
sudo apt-get install python3-mysqldb
Python代码示例:
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")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
2. PostgreSQL
安装PostgreSQL客户端库:
sudo apt-get update
sudo apt-get install python3-psycopg2
Python代码示例:
import psycopg2
# 连接数据库
conn = psycopg2.connect(host="localhost", database="your_database", user="your_username", password="your_password")
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
3. SQLite
SQLite是嵌入式数据库,不需要额外的客户端库。
Python代码示例:
import sqlite3
# 连接数据库
conn = sqlite3.connect('your_database.db')
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
4. MongoDB
安装MongoDB驱动:
sudo apt-get update
sudo apt-get install python3-pymongo
Python代码示例:
from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 查询文档
documents = collection.find()
for doc in documents:
print(doc)
5. Redis
安装Redis客户端库:
sudo apt-get update
sudo apt-get install python3-redis
Python代码示例:
import redis
# 连接Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('key', 'value')
# 获取键值对
value = r.get('key')
print(value)
这些示例展示了如何在Ubuntu上使用Python连接不同类型的数据库。根据你的具体需求选择合适的数据库和驱动库。
以上就是关于“Python在Ubuntu上的数据库连接方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm