flask框架学习笔记——连接数据库ORM增删改查

前提条件需要安装flask_sqlalchemy (在虚拟环境(windows系统是/***/scripts 文件夹下 激活虚拟环境activate pip install flask_sqlalchemy ))
用flask_sqlalchemy连接数据库
1、新建一个config.py文件
DIALECT = ‘mysql’
DRIVER = ‘mysqldb’
USERNAME = ‘root’
PASSWORD = ‘password’
HOST = ‘127.0.0.1’
PORT = ‘3306’
DATABASE = ‘mhftest’

SQLALCHEMY_DATABASE_URI = “{}+{}?/{}:{}@{}:{}/{}?charset=utf8”.format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
2、主app.py文件

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

app = Flask (name)
app.config.from_object(config)
db=SQLAlchemy(app)
db.create_all()

@app.route (’/’)
def hello_world():
return ‘Hello World!’

if name == ‘main’:
app.run (debug=True)
3、创建一个表"article"
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config
app = Flask (name)
app.config.from_object(config)
db=SQLAlchemy(app)

class Article(db.Model):
tablename=‘article’
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
title=db.Column(db.String(100),nullable=True)
context=db.Column(db.Text,nullable=False)
db.create_all()
@app.route (’/’)
def hello_world():
return ‘Hello World!’
if name == ‘main’:
app.run (debug=True)
4、article表增加一条记录
@app.route (’/’)
def hello_world():
#增加
art1=Article(title=‘aaa’,context=‘bbb’)
db.session.add (art1)
db.session.commit()
return ‘Hello World!111’
if name == ‘main’:
app.run (debug=True)
前台登录访问http://127.0.0.1:5000/ 刷新一次表中增加一条记录
5、增删改查
@app.route (’/’)
def hello_world():
# #增加
# art1=Article(title=‘aaa’,context=‘bbb’)
# db.session.add (art1)
# db.session.commit()
# #查
# article1=Article.query.filter(Article.title==‘aaa’).first()
# print(‘article1.titel %s’%article1.title)
# print(‘article1.context %s’%article1.context)
# #改
# article1=Article.query.filter(Article.title==‘aaa’).first()
# article1.title=‘new_aaa’
# db.session.commit()
#删
article1=Article.query.filter(Article.title==‘new_aaa’).first()
db.session.delete(article1)
db.session.commit()
return ‘Hello World!123’
if name == ‘main’:
app.run (debug=True)

你可能感兴趣的:(pycharm,flask)