from sqlalchemy import Column, String, create_engine, Integer, Date, Float, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
def get_session():
engine = create_engine('mysql+pymysql://root:root@10.10.10.11:9000/mysqldb?charset=utf8')
DBSession = sessionmaker(bind=engine)
session = DBSession()
return session
Base = declarative_base()
class Asset(Base):
__tablename__ = 'hr_asset'
id = Column(Integer, primary_key=True)
assetnum = Column(String(50))
assetname = Column(String(50))
assetmodel = Column(String(50))
assettype = Column(Integer)
assetstate = Column(Integer)
usepersonid = Column(Integer, ForeignKey("hr_user.id"))
userperson = relationship("User",backref="asset", uselist=False)
class User(Base):
__tablename__ = 'hr_user'
id = Column(Integer, primary_key=True)
username = Column(String(50))
age = Column(Integer)
degree = Column(String(50))
if __name__ == "__main__":
try:
session1 = get_session()
new_user = User(username='龙九', age=33, degree="本科")
session1 .add(new_user)
session1 .commit()
the_id=new_user.id
session1 .close()
except:
pass
if __name__ == "__main__":
try:
session2 = get_session()
session2.query(User).filter(User.id == '3').delete()
session2.commit()
session2.close()
except:
pass
if __name__ == "__main__":
try:
session3 = get_session()
session3.query(User).filter(User.id == '2').update({User.degree: '高中'}, synchronize_session=False)
session3.commit()
session3.close()
except:
pass
if __name__ == "__main__":
try:
session3 = get_session()
the_user = session3.query(User).get(2)
the_user.username ="小王"
the_user.age= 40
the_user.degree ="博士"
session3.commit()
session3.close()
except:
pass
if __name__ == "__main__":
try:
session4 = get_session()
user = session4.query(User).filter(User.id == 3).one()
print('type:', type(user))
print('name:', user.username)
session4.close()
except:
pass
if __name__ == "__main__":
try:
session5 = get_session()
users = session5.query(User).filter(User.id > 0).all()
for i in range(len(users)):
print(users[i].id)
print(users[i].username)
session5.close()
except:
pass
if __name__ == "__main__":
try:
session6 = get_session()
assets = session6.query(Asset).join(User).filter(User.id > 0).all()
for i in range(len(assets)):
pass
session6.close()
except:
pass
打开App,阅读手记