#encoding: utf-8 from sqlalchemy import create_engine,Column,Integer,String,DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker HOSTNAME = '127.0.0.1' PORT = 3306 DATABASE = 'first_sqlalchemy' USERNAME = 'root' PASSWORD = '123456' #dialect+driver://username:password@host:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) session = sessionmaker(engine)() from datetime import datetime class Article(Base): __tablename__ = 'article' id = Column(Integer,primary_key=True,autoincrement=True) #name的用处就是更改在title在数据库中的名字,就是其别名 title = Column(String(50),nullable=False,name='article_title') describe = Column(String(200),unique=True,nullable=False) read_count = Column(Integer,default=0) #onupdate,只有更新数据的时候才有用 update_time = Column(DateTime,onupdate=datetime.now,default=datetime.now) create_time = Column(DateTime,default=datetime.now) Base.metadata.drop_all() Base.metadata.create_all() # article = Article(title = '武动乾坤') # session.add(article) # session.commit() article = Article(title = '武动乾坤',describe = 'wuwuwuwuwuwuwu') session.add(article) session.commit() #验证下ondate的作用 # article = session.query(Article).first() # article.title = '斗破苍穹' # session.commit()