在Python中,使用ORM(對(duì)象關(guān)系映射)框架可以簡(jiǎn)化數(shù)據(jù)庫(kù)連接和操作。一個(gè)流行的ORM框架是SQLAlchemy。以下是使用SQLAlchemy連接和操作數(shù)據(jù)庫(kù)的步驟:
pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 替換為你的數(shù)據(jù)庫(kù)連接字符串
DATABASE_URI = 'sqlite:///example.db'
engine = create_engine(DATABASE_URI)
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='John Doe', age=30)
session.add(new_user)
session.commit()
# 查詢(xún)記錄
users = session.query(User).all()
for user in users:
print(user.id, user.name, user.age)
# 更新記錄
user_to_update = session.query(User).filter_by(name='John Doe').first()
user_to_update.age = 31
session.commit()
# 刪除記錄
user_to_delete = session.query(User).filter_by(name='John Doe').first()
session.delete(user_to_delete)
session.commit()
# 關(guān)閉會(huì)話(huà)
session.close()
以上示例展示了如何使用SQLAlchemy ORM框架連接到數(shù)據(jù)庫(kù)并執(zhí)行基本的CRUD操作。你可以根據(jù)自己的需求修改數(shù)據(jù)模型和數(shù)據(jù)庫(kù)連接字符串。