sqlalchemy database operations

1 Introduction

One kind of ORM

2, installation

pip3 install -i https://pypi.douban.com/simple sqlalchemy

3, the database connection

 from SQLAlchemy Import create_engine 
 Engine = create_engine (
         " MySQL + pymysql: // root: password @ 127.0.0.1:? 3306 / database name = utf8 charset " , 
        max_overflow = 0,   # exceed the size of the largest connected to the external connection pool created 
        pool_size = 5 ,   # connection pool size 
        pool_timeout = 30,   # pool is no time thread waits up, otherwise an error 
        pool_recycle = -1   # long threads in the pool after recovering a connection (reset) 
    )

4, create / delete tables (database contains the connection)

a, table class

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer,String

Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=False)
    depart_id = Column(Integer)

b, create / delete tables

from SQLAlchemy Import create_engine
 DEF create_all (): 
    Engine = create_engine (
         " MySQL + pymysql: // root: password @ 127.0.0.1:? 3306 / database = utf8 charset " , 
        max_overflow = 0,   # than most outside connections pool size created connecting 
        pool_size =. 5,   # connection pool size 
        pool_timeout = 30,   # pool is no time thread waits up, otherwise an error 
        pool_recycle = -1   # how long after the threads in the pool of a connection recovery (reset) 
    ) 

    Base. metadata.create_all (Engine) 

DEF drop_all (): 
    Engine = create_engine (
         "mysql + pymysql: // root: password @ 127.0.0.1:? 3306 / database = utf8 charset " , 
        max_overflow = 0,   # exceed the size of the largest connected to the external connection pool created 
        pool_size = 5,   # connection pool size 
        pool_timeout = 30,   # pool has no thread waits up time, otherwise an error 
        pool_recycle = -1   # how long after the threads in the pool of recovery (reset) connected at one time 
    ) 
    Base.metadata.drop_all (Engine) 

IF  the __name__ == ' __main__ ' :
     # drop_all () 
    create_all ()

 

Note: sqlalchemy table class unlike the django orm that can update, delete and rebuild only

Guess you like

Origin www.cnblogs.com/wt7018/p/11616502.html