我们提供的服务有:网站建设、做网站、微信公众号开发、网站优化、网站认证、平鲁ssl等。为上千余家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的平鲁网站制作公司
#Author Kang
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
#创建对象的基类:
Base = declarative_base()
#定义User对象:
class User(Base):
#表的名字:
__tablename__ = 'user'
#表的结构:
userid = Column(Integer,primary_key=True)
username = Column(String(20))
age = Column(Integer)
department = Column(String(20))
salary = relationship("Salary",backref="test")
#def __repr__(self):
# return "userid:%s name:%s age:%s department:%s money:%s "%(self.userid,self.username,self.age,self.department,self.salary[0])
#定义Salary对象:
class Salary(Base):
#表的名字:
__tablename__ = 'salary'
#表的结构:
id = Column(Integer,primary_key=True)
userid = Column(Integer,ForeignKey("user.userid"))
month = Column(Integer)
money = Column(Integer)
def __repr__(self):
return "%s" % (self.money)
#初始化数据库连接
engine = create_engine("MySQL+pymysql://kang:123456@10.3.152.35/test",encoding="utf-8")
#创建session类型
DBSession = sessionmaker(bind=engine)
#创建session对象
session = DBSession()
print("Salary表,通过backref反向查询User的姓名信息>>>>>>>>>>>>>>")
e1 = session.query(Salary).filter_by(userid=3).first()
print(e1.test.username,e1.money)
print("user表,正向查询salary工资信息>>>>>>>>>>>>>>>>>>>>>>>>")
res = session.query(User).filter_by(username='MingKang').first()
print(res.username,res.salary[0])
Salary表,通过backref反向查询User的姓名信息>>>>>>>>>>>>>>
MingKang 12000
user表,正向查询salary工资信息>>>>>>>>>>>>>>>>>>>>>>>>
MingKang 12000