Python 包 SQLAlchemy 有一个 ORM 层,但它也有一个 SQL 生成层。
[我知道你标记了这篇文章 c# 和 .net,但我想你可能想看看还有什么]
这是一些示例代码:
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.sql import select
metadata = MetaData()
# Make a basic customer table.
Customer = Table('Customer',
metadata,
Column('ID', Integer, primary_key=True),
Column('FirstName', String),
Column('LastName', String))
# Make a basic address table
Address = Table('Address',
metadata,
Column('ID', Integer, primary_key=True),
Column('City', String),
Column('Street', String),
Column('CustomerID', None, ForeignKey('Customer.ID')))
# Generate some sql
stmt = select([Customer.c.FirstName,
Customer.c.LastName,
Address.c.Street,
Address.c.City],
from_obj=Customer.join(Address),
whereclause=Address.c.City == 'Wellington')
# Display
print stmt
# output:
SELECT "Customer"."FirstName", "Customer"."LastName", "Address"."Street", "Address"."City"
FROM "Customer" JOIN "Address" ON "Customer"."ID" = "Address"."CustomerID"
WHERE "Address"."City" = :City_1
# note that SQLAlchemy picked up the join condition from the foreign key.
# you can specify other join conditions if you want.
通常,您将通过使用 SQLAlchemy 连接到数据库来执行该语句。然后你可以这样做:
for row in stmt.execute():
print 'Name:', row.c.FirstName, row.c.LastName, 'City:', row.c.City
希望这可以帮助。