# -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
# 数据库连接url
DB_CONNECT_STRING = "mysql+pymysql://user:passwd@127.0.0.1:3306/dbname?charset=utf8"
# 创建引擎
engine = create_engine(DB_CONNECT_STRING, echo=True)
# 自动映射
Base = automap_base()
Base.prepare(engine, reflect=True)
# 获取所有表的映射类 ['book','user']
# tables = Base.classes.keys()
# print(tables)
# 获取指定类user表 --> user实体类
User = Base.classes.user
# 查看User
# print(User.__dict__)
# 获取所有字段或属性 ['id', 'name']
# keys = User.__table__.columns.keys()
# print(keys)
# 创建session
Session = sessionmaker(bind=engine)
session = Session()
# 按条件查表, 返回实例集合
user = session.query(User).filter(User.id=='1').first()
print('id', user.id)
print('name:', user.name)
# 创建新的实例,并插入,nowtime字段为TIMESTAMP
newUser = User(id='6', name='chen')
session.add(newUser)
# 提交
session.commit()
session.close()