Creating tables and adding data
Import SQLAlchemy
From SQLAlchemy import Create_engine
From sqlalchemy.ext.declarative import declarative_base
From SQLAlchemy import Column, Integer, String
From Sqlalchemy.orm import Sessionmaker
Engine = Create_engine ("Mysql+pymysql://root:[email protected]/test_db", echo=true) #echo =true can view more information
Base = Declarative_base ()
#创建表
Class User (Base):
__tablename__ = ' user ' #表名
id = Column (Integer, Primary_key=true)
Name = Column (String (32))
Password = Column (String (64))
def __repr__ (self): #显示ORM查询执行后的结果 (no memory address returned by this method)
Return '%s:%s '% (Self.name, Self.password)
Base.metadata.create_all (engine) #创建表结构
#创建连接
Session_class = Sessionmaker (bind=engine) #创建与数据库的会话session class, notice that the return is a class, not an instance
Session = Session_class () #生成session实例 #可以先理解成curson游标
#查询
# data = Session.query (User). Filter (User.ID < 2). All () #是一个列表
data = Session.query (User). Filter (User.ID > 2). Filter (User.ID < 5)
Print (data)
#插入数据
User_obj1 = User (name= ' Lizhao ', password= ' lizhaoqwe123 ') #生成要创建的数据对象
User_ibj2 = User (name= ' test ', password= ' testqwe123 ')
Session.add (USER_OBJ1)
Session.add (USER_IBJ2)
Session.commit () #必须commit之后才会添加数据
ORM Operation MySQL