Flask框架使用SQLite数据库
SQLite数据库
SQLite是一款轻型的数据库,遵守ACID的关系型数据库管理系统,占用资源非常的低,能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Python、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。
SQLite3为SQLite的第一个版本。
其特点为:
- 零配置,无需安装和管理配置;
- 储存在单一磁盘文件中的一个完整的数据库;
- 数据库文件可以在不同字节顺序的机器间自由的共享;
- 足够小, 大致13万行C代码, 4.43M,支持数据库大小可至2TB;
- 数据库操作快;
- 不需要任何外部的依赖。
创建SQLite数据库
创建Flask项目并在项目目录下创建名为test.py文件
test.py文件作用为创建SQLite数据库,代码如下所示:
import sqlite3 conn = sqlite3.connect('database.db') #建立database.db数据库连接 conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') #执行单条sql语句 conn.close() #关闭连接
创建SQLite数据库很简单:建立连接——创建数据表——关闭连接。
使用sqlite3.connect()创建数据库连接,当连接的数据库不存在时,会自动在test.py文件同级路径下创建数据库,再使用execute()方法创建数据表,最后.close()关闭连接。
其中SQLite数据库存储的数据表值类型有:
存储类 | 描述 |
---|---|
NULL | 值是一个 NULL 值。 |
INTEGER | 值是一个带符号的整数,根据值的大小存储在 1、2、3、4、6 或 8 字节中。 |
REAL | 值是一个浮点值,存储为 8 字节的 IEEE 浮点数字。 |
TEXT | 值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储。 |
BLOB | 值是一个 blob 数据,完全根据它的输入存储 |
好了,运行test.py可以发现在项目目录中创建了一个名为database的数据库。
使用SQLite
首先在app.py文件中编写create_student视图函数,代码如下所示:
@app.route('/create') def create_student(): return render_template('student.html') #渲染student.html模板
使用render_template()方法渲染student.html模板,student.html模板代码如下所示:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <form action = "{{ url_for('add_student') }}" method = "POST"> <p>姓名<input type = "text" name = "nm" /></p> <p>地址<textarea name = "add" ></textarea></p> <p>城市<input type = "text" name = "city" /></p> <p>邮编<input type = "text" name = "pin" /></p> <input type = "submit" value = "提交" /> </form> </body> </html>
使用url_for()方法将表单中的数据传递到视图函数add_student中,该视图函数代码如下所示:
@app.route('/addstudent',methods = ['POST', 'GET']) def add_student(): try: #获取请求中的nm、add、city、pin的数据 nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sqlite3.connect("database.db") as con: #建立与database.db数据库的连接 cur = con.cursor() #获取游标 cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) #添加数据,执行单条的sql语句 con.commit() #提交事务 msg = "数据添加成功" except: con.rollback() #撤消当前事务中所做的所有更改 msg = "操作失败" finally: return render_template("result.html",msg = msg) #渲染result.html模板并传递msg值 con.close() #关闭数据库连接
首先获取请求中的数据,在建立与database.db数据库连接,使用.cursor()获取数据库游标,在使用execute()方法添加数据,执行单条sql语句,最后提交事务,当数据添加失败时,调用rollback()方法撤消当前事务中所做的所有更改,使用render_template()方法渲染result.html模板并传递msg值。
result.html模板代码如下所示:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> 操作结果 : {{ msg }} </body> </html>
接下来编写展示数据的视图函数show_student,代码如下所示:
@app.route('/show') def show_student(): con = sqlite3.connect("database.db") #建立数据库连接 con.row_factory = sqlite3.Row #设置row_factory,对查询到的数据,通过字段名获取列数据 cur = con.cursor() #获取游标 cur.execute("select * from students") #执行sql语句选择数据表 rows = cur.fetchall() #获取多条记录数据 return render_template("show.html",rows = rows) #渲染show.html模板并传递rows值
建立数据库连接并设置row_factory对象查询到的数据通过字段名来获取列数据,使用cursor()方法获取数据操作游标,再使用execute()方法执行sql语句选择数据表,使用fetchall()放过获取多条数据,最后使用render_template方法渲染show.html模板并传递rows值。
show.html模板代码如下所示:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Title</title> </head> <body> <table border = 1> <thead> <td>改名</td> <td>地址</td> <td>城市</td> <td>编码</td> </thead> {% for row in rows %} <tr> <td>{{row["name"]}}</td> <td>{{row["addr"]}}</td> <td>{{row["city"]}}</td> <td>{{row['pin']}}</td> </tr> {% endfor %} </table> </body> </html>
启动Flask程序,访问http://127.0.0.1:5000/create写入数据,如下图所示