当前位置:   article > 正文

Java之于mybatis,Python之于sqlalchemy_java mybatis python

java mybatis python
pip install pymysql
pip install sqlalchemy
  • 1
  • 2

测试


from sqlalchemy import Column, String, Integer, and_, text
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import time

engine = create_engine("mysql+pymysql://root:123456@192.168.154.134:3306/jwolf", echo=True)
Session = sessionmaker(bind=engine)
session = Session()

# 需要继承基类
Base = declarative_base()
class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    name = Column(String(20), default=None, nullable=False, comment="用户姓名")
    phone = Column(String(20), default=None, nullable=False, comment="电话")
    country = Column(Integer, default=0, nullable=False, comment="国家")

class User2(Base):
    __tablename__ = "user2"
    id = Column(Integer, primary_key=True)
    name = Column(String(20), default=None, nullable=False, comment="用户姓名")
    phone = Column(String(20), default=None, nullable=False, comment="电话")
    country = Column(Integer, default=0, nullable=False, comment="国家")


if __name__ == '__main__':
    # 基于Base的实现类创建表,这里会创建user,user2两个表
    Base.metadata.create_all(engine)
    # 通过Entity实现DB操作
    new_user = User(name=time.localtime(), phone="12345678910", country=666)
    session.add(new_user)
    session.commit()
    #list = session.query(User).filter(User.id >=1).filter(User.id <=2 )
    list = session.query(User).filter(and_(User.id >=1,User.id <=2))
    print([user.name for user in list])
    # 通过SQL实现DB操作
    with engine.connect() as conn:
        cursor_result = conn.execute(text("select * from user"))
        print(cursor_result.all())

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/613180
推荐阅读
相关标签
  

闽ICP备14008679号