ubuntu

Ubuntu Python与数据库交互方法

小樊
43
2025-03-30 17:43:59
栏目: 编程语言

在Ubuntu上使用Python与数据库进行交互,通常会使用一些流行的数据库驱动程序和ORM(对象关系映射)库。以下是一些常见的数据库及其对应的Python交互方法:

1. MySQL

安装MySQL客户端库

sudo apt-get update
sudo apt-get install python3-mysqldb

Python代码示例

import mysql.connector

# 连接数据库
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

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

# 执行SQL查询
mycursor.execute("SELECT * FROM customers")

# 获取所有记录
myresult = mycursor.fetchall()

for x in myresult:
  print(x)

# 关闭连接
mydb.close()

2. PostgreSQL

安装PostgreSQL客户端库

sudo apt-get update
sudo apt-get install python3-psycopg2

Python代码示例

import psycopg2

# 连接数据库
conn = psycopg2.connect(
    dbname="yourdatabase",
    user="yourusername",
    password="yourpassword",
    host="localhost"
)

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

# 执行SQL查询
cur.execute("SELECT * FROM customers")

# 获取所有记录
rows = cur.fetchall()

for row in rows:
    print(row)

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

3. SQLite

SQLite是一个轻量级的数据库,不需要单独的服务器进程。

Python代码示例

import sqlite3

# 连接数据库
conn = sqlite3.connect('example.db')

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

# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS customers
               (id INTEGER PRIMARY KEY, name TEXT, address TEXT)''')

# 插入数据
cursor.execute("INSERT INTO customers (name, address) VALUES ('John Doe', '123 Main St')")

# 提交事务
conn.commit()

# 查询数据
cursor.execute("SELECT * FROM customers")
rows = cursor.fetchall()

for row in rows:
    print(row)

# 关闭连接
conn.close()

4. MongoDB

MongoDB是一个NoSQL数据库,使用Python的pymongo库进行交互。

安装MongoDB客户端库

pip install pymongo

Python代码示例

from pymongo import MongoClient

# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')

# 选择数据库
db = client['yourdatabase']

# 选择集合
collection = db['customers']

# 插入文档
document = {"name": "John Doe", "address": "123 Main St"}
collection.insert_one(document)

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

使用ORM(对象关系映射)

ORM库如SQLAlchemy可以简化数据库操作,提供更高层次的抽象。

安装SQLAlchemy

pip install sqlalchemy

Python代码示例

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 定义模型
Base = declarative_base()

class Customer(Base):
    __tablename__ = 'customers'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    address = Column(String)

# 创建数据库引擎
engine = create_engine('sqlite:///example.db')

# 创建表
Base.metadata.create_all(engine)

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()

# 添加记录
new_customer = Customer(name='John Doe', address='123 Main St')
session.add(new_customer)
session.commit()

# 查询记录
customers = session.query(Customer).all()
for customer in customers:
    print(customer.name, customer.address)

# 关闭会话
session.close()

以上是Ubuntu上使用Python与不同数据库进行交互的基本方法。根据具体需求选择合适的数据库和工具。

0
看了该问题的人还看了