温馨提示×

Ubuntu中Python数据库连接怎么实现

小樊
52
2025-07-27 20:06:45
栏目: 编程语言

在Ubuntu系统中,使用Python连接数据库通常需要安装相应的数据库驱动。以下是几种常见数据库的连接方法:

1. 连接MySQL数据库

安装MySQL客户端库

sudo apt update
sudo apt install python3-mysqldb

Python代码示例

import MySQLdb

# 连接到数据库
db = MySQLdb.connect(host="localhost", user="your_username", passwd="your_password", db="your_database")

# 创建游标对象
cursor = db.cursor()

# 执行SQL查询
cursor.execute("SELECT VERSION()")

# 获取单条数据
data = cursor.fetchone()
print("Database version : %s " % data)

# 关闭数据库连接
db.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"
)

# 创建游标对象
cur = conn.cursor()

# 执行SQL查询
cur.execute("SELECT version();")

# 获取单条数据
db_version = cur.fetchone()
print("PostgreSQL database version:", db_version)

# 关闭游标和连接
cur.close()
conn.close()

3. 连接SQLite数据库

SQLite是一个嵌入式数据库,不需要额外的客户端库。

Python代码示例

import sqlite3

# 连接到SQLite数据库(如果不存在则会自动创建)
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()

# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
                  (date text, trans text, symbol text, qty real, price real)''')

# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2023-04-01','BUY','RHAT',100,35.14)")

# 提交事务
conn.commit()

# 查询数据
cursor.execute("SELECT * FROM stocks")
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭游标和连接
cursor.close()
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": "Alice", "age": 25}
collection.insert_one(document)

# 查询文档
for doc in collection.find():
    print(doc)

总结

以上是几种常见数据库在Ubuntu系统中使用Python连接的示例。根据你的具体需求选择合适的数据库和相应的驱动库进行连接和操作。

0