且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQLAchemy Core学习之Reflection

更新时间:2022-08-21 22:34:38

如果以后万一有一个定义好了的库,可以用这种反射的方法,作常用的操作。

#coding=utf-8

from datetime import datetime
from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String, Boolean, 
                        DateTime, ForeignKey, create_engine, CheckConstraint)
from sqlalchemy import (insert, select, update, delete, text, desc, cast, and_, or_, not_)
from sqlalchemy import (Table, ForeignKeyConstraint)
from sqlalchemy.sql import func
from sqlalchemy.exc import IntegrityError

metadata = MetaData()
engine = create_engine('mysql+pymysql://u:p@ip:3306/Chinook')

artist = Table('Artist', metadata, autoload=True, autoload_with=engine)

print artist.columns.keys()

s = select([artist]).limit(10)
print engine.execute(s).fetchall()

album = Table('Album', metadata, autoload=True, autoload_with=engine)
album.append_constraint(ForeignKeyConstraint(['ArtistId'], ['artist.ArtistId']))

print album.columns.keys()
print metadata.tables

print album.foreign_keys

# print str(artist.join(album))

metadata.reflect(bind=engine)
print metadata.tables.keys()

playlist = metadata.tables['Playlist']
s = select([playlist]).limit(10)
print engine.execute(s).fetchall()

SQLAchemy Core学习之Reflection