post访问方式
一般情况下,网页的直接访问方式只有get形式,如果想要提交post表单,需要在修饰器中声明methods有post方式,才可以提交post表单;即:
@app.route("/lib",methods=['GET','POST'])
如果需要使用post请求来跳转页面就加上if语句,在访问方式变为post时进行一个跳转的变换:
if request.method == 'POST':
还可以使用request函数来获取请求的内容和请求的数据,两个语句分别为:
#其中f是指定的复选框的名称
request.form['f']
#get是获取数据,key是指定文本输入框的名字
request.form.get('key')
sql语句书写方式
空格空格一定要注意空格!
sql语句中或其他语句中都要注意空格的存在,所有在进行sql语句拼接时,要注意在where前后加上空格,其他的条件也是这样,比如name或id等都要注意前后有空格;
参数化
sql语句可以参数化,使用%即可,在语句中加入%s,在引号外可以加上%s来代替缺失的语句,或者在调用sql语句来访问数据库时加上参数:
sql3 = sql + " where " + request.form['f'] + " = '%s'" % request.form.get('key')
sql4 = "select count(*) from imd_copybook where book_id = %s"
cursor.execute(sql4,two[5])
sql5 = "select count(*) from imd_copybook where is_borrow=1 and status=1 and book_id= %s"
cursor.execute(sql5, two[5])
注意最后导出的元组中元素的数量
其实先找一个列表来存放数据,最后把整个列表导入另外一个列表中,只会有一个数据,所以最后在新的页面中就算是循环,也只会有一个表格,而不是出现多个表格,注意这一点,如果是分批次导入数据,那么会出现很多个表格,并且有的表格会缺失数据;
最后是完整的代码:
py:
from flask import Flask, render_template,request
import pymysql
app = Flask(__name__)
#路由默认只支持get,如果需要增加,需要自行指定
@app.route("/lib",methods=['GET','POST'])
def index():
# 连接数据库的四个要素(端口号默认3306,已省略)
hostName = "localhost"
userName = "root"
userPassword = "root"
dbName = "study11"
# 使用connect方法进行连接MySQL
# 函数
db = pymysql.connect(hostName, userName, userPassword, dbName)
# 我们需要一个游标
cursor = db.cursor()
# 编写SQL
sql = "select * from imd_book"
# sql = """insert into imd_book (isdn,publish_date,author,publisher,name,bookid)
# values ('188XXX188','2007/2/3','施耐庵','中国出版社','水浒传',21)"""
#sql = "delete from imd_book where bookid=17"
#馆藏副本总数
sql1 = "select count(*) from imd_copybook where book_id = %s"
#馆藏可借总数 is_borrow=1可借 stautus=1未被借走
sql2 = "select count(*) from imd_copybook where is_borrow=1 and status=1 and book_id= %s"
try:
# 执行SQL,使用execute方法执行
cursor.execute(sql)
# 获取数据
results = cursor.fetchall()
#print(results)
# 循环显示数据
datalist = []
for row in results:
#每一次循环都把one列表变成空列表
one = [<