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__)
# 查询数据 @app.route('/') def index(): conn = sqlite3.connect(os.path.join(BASE_DIR, 'wxs.db')) cursor = conn.cursor() sql = "select id,title from blog" rows = cursor.execute(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)
# 添加一条新数据 @app.route("/add_blog/",methods=['GET','POST']) def add_blog(): if request.method == 'GET': return render_template('add_blog.html') else: conn = sqlite3.connect(os.path.join(BASE_DIR,'wxs.db')) cursor = conn.cursor() title = request.form.get('title') content = request.form.get('content') sql = "insert into blog(id,title,content) values(null,'%s','%s')"%(title,content) cursor.execute(sql) conn.commit() conn.close() print("title:%s"%title) print("content:%s"%content) return redirect('/')
# 通过get请求,查询参数获取一条数据 @app.route("/blog_detail/") def blog_detail():
# args 查询参数 ?id=内容 blog_id = request.args.get("id") conn = sqlite3.connect(os.path.join(BASE_DIR, 'wxs.db')) cursor = conn.cursor() sql = "select id,title,content from blog where id=%s"%blog_id rows = cursor.execute(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()
https://www.cnblogs.com/WiseAdministrator/