python-SQLAlchemy详解
时间:2021-07-01 10:21:17
帮助过:16人阅读
导入:
from sqlalchemy
import Column, String, create_engine,ForeignKey
from sqlalchemy.orm
import sessionmaker,relationship
from sqlalchemy.ext.declarative
import declarative_base
# 创建对象的基类:
Base =
declarative_base()
# 初始化数据库连接(postgresql默认使用psycopg2驱动,可省略):
engine = create_engine(
‘postgresql+psycopg2://username:password@host:post/dbname‘)
# 创建DBSession类型:
DBSession = sessionmaker(bind=
engine)
# 定义User对象:
class User(Base):
# 表的名字:
__tablename__ =
‘test2‘
# 表的结构:
id = Column(String(20), primary_key=
True)
name = Column(String(20
))
# 一对多:
books=relationship(
‘Book‘)
class Book(Base):
# 表的名字:
__tablename__ =
‘test3‘
# 表的结构:
id = Column(String(20), primary_key=
True)
name = Column(String(20
))
# “多”的一方的book表是通过外键关联到user表的:
user_id=Column(String(20),ForeignKey(
‘test2.id‘))
session=
DBSession()
new_user=User(id=
‘5‘,name=
‘Bob‘)
session.add(new_user)
new_book=Book(id=
‘1‘,name=
‘linux‘,user_id=
‘5‘)
session.add(new_book)
new_book=Book(id=
‘2‘,name=
‘python‘,user_id=
‘5‘)
session.add(new_book)
session.commit()
session.close()
session=
DBSession()
user=session.query(User).filter(User.id==
‘5‘).one()
print ‘type:‘,type(user)
print ‘name:‘,user.name
print ‘books:‘,user.books
session.close()
运行结果:
python-SQLAlchemy详解
标签:primary pre on() 连接 prim nmake for creat bind