您好,登錄后才能下訂單哦!
#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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。