ubuntu

Python在Ubuntu上的数据库连接方法

小樊
53
2025-09-08 19:42:20
栏目: 编程语言

在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连接不同类型的数据库。根据你的具体需求选择合适的数据库和驱动库。

0
看了该问题的人还看了