models.py
From sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import columnfrom sqlalchemy import Integer, String,text,date,datetimefrom sqlalchemy Import create_enginebase = Declarative_base () class Users (base): __tablename_ _ = ' users ' id = column (Integer, primary_key=true) name = Column (String (+), Index=true, Nullable=false) def create_a LL (): engine = Create_engine ("Mysql+pymysql://root:[email protected]:3306/s9day120?charset=utf8", M ax_overflow=0, # More connections than connection pool size created pool_size=5, # Connection Pool size pool_timeout=30, # No threads in the pool wait most time, otherwise error pool_r Ecycle=-1 # How long after a connection to a thread in a thread pool is recycled (reset)) Base.metadata.create_all (engine) def drop_all (): Engine = Create_engine ( "Mysql+pymysql://root:[email protected]:3306/s9day120?charset=utf8", max_overflow=0, # More connections than connection pool size created pool_size=5, # Connection Pool size pool_timeout=30, # No threads in the pool wait the most time, otherwise the error pool_recycle=-1 # How long after the thread in the thread pool to make a connection back (reset)) Base.metadata.drop_All (engine) if __name__ = = ' __main__ ': Create_all ()
views.py
From sqlalchemy.orm import sessionmakerfrom sqlalchemy import create_enginefrom models import users# Create engine engines = Create_e Ngine ( "Mysql+pymysql://root:[email Protected]:3306/s9day120?charset=utf8", max_overflow=0, # More connections than connection pool size created pool_size=5, # Connection Pool size pool_timeout=30, # No threads in the pool wait most time, otherwise error Pool_recycle=-1 # How long it takes to recycle (reset) A connection to a thread in a thread pool # Session factory created according to engine sessionfactory = Sessionmaker (bind=engine) # Create a Session object with session factory session = Sessionfactory () ... # According to the users category, the users table has been increased and censored ... # close sessionsession.close (). #
Operation
Increase
obj = Users (name= ' Alex ') Session.add (obj) session.commit () Session.add_all ([ Users (name= ' small Northeast '), users ( Name= ' Dragon Thai ')] Session.commit ()
Delete
Session.query (Users). Filter (Users.id >= 2). Delete () Session.commit ()
Change
Session.query (Users). filter (Users.id = = 4). Update ({users.name: ' Northeast '}) session.query (users). filter (Users.id = = 4). Update ({' name ': ' Small Northeast '}) session.query (Users). Filter (Users.id = = 4). Update ({' name ': users.name+ "DSB"},synchronize_ Session=false) Session.commit ()
Check
result = Session.query (users). All () for row in result: print (row.id,row.name) result = Session.query (users). Filter ( Users.id >= 2) for row in result: print (row.id,row.name) result = Session.query (Users). Filter (Users.id >= 2). First () print (result)
Flask using SQLAlchemy to connect to MySQL