阅读量:4
在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接方法:
1. 连接MySQL数据库
安装MySQL客户端库
sudo apt update
sudo apt 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 VERSION()")
# 获取单条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭连接
conn.close()
2. 连接PostgreSQL数据库
安装PostgreSQL客户端库
sudo apt update
sudo apt install python3-psycopg2
Python代码示例
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 version();")
# 获取单条数据
db_version = cursor.fetchone()
print("Database version : %s " % db_version)
# 关闭连接
conn.close()
3. 连接SQLite数据库
SQLite是一个嵌入式数据库,不需要额外的客户端库。
Python代码示例
import sqlite3
# 连接数据库
conn = sqlite3.connect('your_database.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT sqlite_version();")
# 获取单条数据
sqlite_version = cursor.fetchone()
print("SQLite version : %s " % sqlite_version)
# 关闭连接
conn.close()
4. 连接MongoDB数据库
安装MongoDB客户端库
sudo apt update
sudo apt install python3-pymongo
Python代码示例
from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 插入文档
document = {"name": "John", "age": 30}
collection.insert_one(document)
# 查询文档
for doc in collection.find():
print(doc)
总结
- MySQL: 使用
python3-mysqldb - PostgreSQL: 使用
python3-psycopg2 - SQLite: 内置支持,无需额外库
- MongoDB: 使用
python3-pymongo
根据你的需求选择合适的数据库和相应的Python库进行连接和操作。
以上就是关于“Python在Ubuntu上如何进行数据库连接”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm