在Python中进行数据库操作时,ORM(对象关系映射)并不是唯一的途径。ORM是一种将数据库表映射到Python对象的技术,它可以帮助开发者以面向对象的方式操作数据库,而不需要直接编写SQL语句。虽然ORM在很多场景下非常方便,但它并不是唯一的选择。以下是几种常见的数据库操作方式:
你可以直接使用SQL语句来操作数据库。Python提供了多种数据库连接库(如sqlite3
、psycopg2
、mysql-connector-python
等),通过这些库,你可以直接执行SQL语句。
示例: ```python import sqlite3
# 连接到SQLite数据库 conn = sqlite3.connect('example.db') cursor = conn.cursor()
# 创建表 cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# 插入数据 cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
# 查询数据 cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row)
# 提交事务并关闭连接 conn.commit() conn.close() ```
ORM工具(如SQLAlchemy、Django ORM、Peewee等)可以将数据库表映射为Python类,表中的每一行对应一个对象。ORM提供了更高层次的抽象,使得开发者可以以面向对象的方式操作数据库。
示例(使用SQLAlchemy): ```python from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker
# 创建数据库连接 engine = create_engine('sqlite:///example.db') Base = declarative_base()
# 定义模型 class User(Base): tablename = 'users' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer)
# 创建表 Base.metadata.create_all(engine)
# 创建会话 Session = sessionmaker(bind=engine) session = Session()
# 插入数据 new_user = User(name='Alice', age=30) session.add(new_user) session.commit()
# 查询数据 users = session.query(User).all() for user in users: print(user.name, user.age)
# 关闭会话 session.close() ```
查询构建器(如SQLAlchemy Core、PonyORM等)提供了一种介于直接SQL和ORM之间的方式。它允许你以编程方式构建SQL查询,而不需要直接编写SQL语句,同时也不强制使用对象映射。
示例(使用SQLAlchemy Core): ```python from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, insert, select
# 创建数据库连接 engine = create_engine('sqlite:///example.db') metadata = MetaData()
# 定义表结构 users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('age', Integer))
# 创建表 metadata.create_all(engine)
# 插入数据 with engine.connect() as conn: stmt = insert(users).values(name='Alice', age=30) conn.execute(stmt)
# 查询数据 with engine.connect() as conn: stmt = select(users) result = conn.execute(stmt) for row in result: print(row) ```
如果你使用的是NoSQL数据库(如MongoDB、Redis等),通常不需要使用ORM。这些数据库通常有自己的Python客户端库,允许你直接操作数据。
示例(使用MongoDB): ```python from pymongo import MongoClient
# 连接到MongoDB client = MongoClient('mongodb://localhost:27017/') db = client['example_db'] collection = db['users']
# 插入数据 user = {'name': 'Alice', 'age': 30} collection.insert_one(user)
# 查询数据 for user in collection.find(): print(user) ```
选择哪种方式取决于你的具体需求、项目规模、团队习惯以及性能要求。