ubuntu

Python在Ubuntu如何与数据库连接

小樊
54
2025-09-06 18:49:16
栏目: 编程语言

在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是一个NoSQL数据库,使用pymongo库进行连接。

安装pymongo库

pip3 install 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)

总结

根据你使用的数据库类型,选择相应的Python库进行安装和连接。常见的数据库包括MySQL、PostgreSQL、SQLite和MongoDB。每种数据库都有其特定的连接方式和操作方法,但基本的连接流程是相似的:安装库、建立连接、执行SQL查询或操作、关闭连接。

0
看了该问题的人还看了