SQLAlchemy操作sqlite3数据库实例:
  项⽬⽬录结构:
  代码:app.py
from flask import Flask,render_template,request,redirect
import sqlite3
import os
app = Flask(__name__)
# directory name:
BASE_DIR = os.path.dirname(__file__)
connect和join的区别# 查询数据
@ute('/')
def index():
conn = t(os.path.join(BASE_DIR, 'wxs.db'))
cursor = conn.cursor()
sql = "select id,title from blog"
rows = ute(sql)
blogs = []
for row in rows:
blog = {}
# (1,'世界杯')
id = row[0]
title = row[1]
blog['id'] = id
blog['title'] = title
blogs.append(blog)
return render_template('index.html',blogs=blogs)
# 添加⼀条新数据
@ute("/add_blog/",methods=['GET','POST'])
def add_blog():
hod == 'GET':
return render_template('add_blog.html')
else:
conn = t(os.path.join(BASE_DIR,'wxs.db'))
cursor = conn.cursor()
title = ('title')
content = ('content')
sql = "insert into blog(id,title,content) values(null,'%s','%s')"%(title,content)
connmit()
conn.close()
print("title:%s"%title)
print("content:%s"%content)
return redirect('/')
# 通过get请求,查询参数获取⼀条数据
@ute("/blog_detail/")
def blog_detail():
  # args 查询参数 ?id=内容
blog_id = ("id")
conn = t(os.path.join(BASE_DIR, 'wxs.db'))    cursor = conn.cursor()
sql = "select id,title,content from blog where id=%s"%blog_id    rows = ute(sql)
blog = {}
for row in rows:
# row = (id,title,content)
blog['id'] = row[0]
blog['title'] = row[1]
blog['content'] = row[2]
return render_template('blog_detail.html',blog=blog)
if__name__ == '__main__':
app.run()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。