Java之于mybatis,Python之于sqlalchemy

pip install pymysql
pip install sqlalchemy

测试


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:[email protected]: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())

你可能感兴趣的:(java,mybatis,python)