ImportSQLAlchemy fromSQLAlchemyImportCreate_engine fromSqlalchemy.ext.declarativeImportDeclarative_base fromSQLAlchemyImportColumn, Integer, String fromSqlalchemy.ormImportSessionmakerengine= Create_engine ('sqlite:///plan.db', encoding='Utf-8') Base= Declarative_base ()#generating an ORM base classclassUser (Base):__tablename__='User' #Table nameid = Column (Integer, primary_key=True) name= Column (String (32)) Password= Column (String (64) ) Base.metadata.create_all (engine)#CREATE TABLE StructureSession_class= Sessionmaker (Bind=engine)#create a session with the database sessions class, note that this is a class that is returned to the session, not an instanceSession = Session_class ()#Generating Session Instances#End of Foundation#Insert StartUser_obj = User (name="Alex", password="alex3714")#build the data object you want to createPrint(User_obj.name, User_obj.id)#No object has been created at this time, do not believe you print the ID found or noneSession.add (user_obj)#Add the data object you want to create to this session, and create a unifiedPrint(User_obj.name, User_obj.id)#This is still not created yet .Session.commit ()#Now this is the unified submission, create data#Insert End#Query StartMy_user = session.query (user). filter_by (name="Alex"). First ()Print(My_user)Print(My_user.id, My_user.name, My_user.password)#End of Query#Modify StartMy_user = session.query (user). filter_by (name="Alex"). First () My_user.name="Alex Li"Session.commit ()#Modify Technology#Multi-Criteria QueryOBJS = Session.query (User). Filter (User.ID > 0). filter (User.ID < 7). All ()#Multi-Criteria Query#StatisticsSession.query (User). Filter (User.name.like ("ra%") . Count ()#Statistics#Grouping fromSQLAlchemyImportfuncPrint(Session.query (Func.count (user.name), User.Name). group_by (User.Name). All ())#Grouping
Python SQLAlchemy Use