#encoding:utf-8 from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) # 数据库增删改查(视图函数中用db.session) #用实例与表数据对应,避免用sql语句来进行增删改查动作 #用类来进行表的映射,一个类就是一个表,一个实例就是一条数据,一个变量属性就是一个字段 class Article(db.Model): #一定要继承db.Model __tablename__ = 'article' id = db.Column(db.Integer,primary_key = True,autoincrement = True) title = db.Column(db.String(100),nullable = False) content = db.Column(db.Text,nullable = False) db.create_all #*************************以上就是服务的开启并监听,创建了一个数据库表Article**************** @app.route('/') def hello_world(): #增加 article1 = Article(title = 'aaa1',content = 'gx1') article2 = Article(title = 'bbb1',content = 'gx2') db.session.add(article1) db.session.add(article2) db.session.commit() #只要一访问浏览器,正确返回了hello world,说明事物提交成功 #查询 sql为 select * from tbname where xxx = 'xxx' result = Article.query.filter(Article.title == 'aaa1').first() #这里要用等号== print result #返回的是实例对象 print result.title #取出对象的title print result.content #取出对象content #改,先查询出来,再来修改 result = Article.query.filter(Article.title == 'aaa1').first() print result result.title = 'aaa111' #将查询出来的所有的title =='aaa1'的记录,全部修改为'aaa111' db.session.commit() #删除 delete from article where content =='bbb' #操作步骤:先查后删除 result = Article.query.filter(Article.content == 'gx1').first() db.session.delete(result) db.session.commit() return "hello world" if __name__ == '__main__': app.run(debug=True)
以下是用到的配置文件config.py
#encoding:utf-8 #dialect+driver://username:password@host:port/database DIALECT = 'mysql' DRIVER = 'mysqldb' USERNAME = 'root' PASSWORD = 'root' HOST = '127.0.0.1' PORT = '3306' DATABASE = 'db_demo2' #mysql 不会认识utf-8,而需要直接写成utf8 SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER, USERNAME,PASSWORD,HOST,PORT,DATABASE) SQLALCHEMY_TRACK_MODIFICATIONS = True