python实现数据库多表查询
作者:野牛程序员:2023-12-22 13:15:29python阅读 2747
在Python中,你可以使用不同的库来连接数据库并执行多表查询。其中,sqlite3和SQLAlchemy是两个常用的库。下面分别介绍它们的基本用法。
使用 sqlite3 进行多表查询
import sqlite3
# 连接到数据库
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
# 执行多表查询
cursor.execute('''
SELECT * FROM table1
JOIN table2 ON table1.id = table2.table1_id
WHERE table1.column_name = 'some_value'
''')
# 获取查询结果
results = cursor.fetchall()
# 处理查询结果
for row in results:
print(row)
# 关闭连接
conn.close()使用 SQLAlchemy 进行多表查询
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
# 定义数据库模型
Base = declarative_base()
class Table1(Base):
__tablename__ = 'table1'
id = Column(Integer, primary_key=True)
column_name = Column(String)
table2_entries = relationship('Table2', back_populates='table1_entry')
class Table2(Base):
__tablename__ = 'table2'
id = Column(Integer, primary_key=True)
table1_id = Column(Integer, ForeignKey('table1.id'))
table1_entry = relationship('Table1', back_populates='table2_entries')
# 连接到数据库
engine = create_engine('sqlite:///your_database.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# 执行多表查询
results = session.query(Table1, Table2).filter(Table1.id == Table2.table1_id).all()
# 处理查询结果
for result in results:
print(result.Table1, result.Table2)
# 关闭连接
session.close()野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

