上篇文章我們學(xué)習(xí)了Flask框架——Flask-Mail郵件硕盹,這篇文章我們學(xué)習(xí)Flask-SQLite數(shù)據(jù)庫(kù)滨砍。
SQLite數(shù)據(jù)庫(kù)
SQLite是一款輕型的數(shù)據(jù)庫(kù)匆笤,遵守ACID的關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),占用資源非常的低,能夠支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時(shí)能夠跟很多程序語(yǔ)言相結(jié)合忽舟,比如Python、C#现拒、PHP、Java等望侈,還有ODBC接口印蔬,同樣比起Mysql、PostgreSQL這兩款開(kāi)源的世界著名數(shù)據(jù)庫(kù)管理系統(tǒng)來(lái)講脱衙,它的處理速度比他們都快侥猬。
SQLite3為SQLite的第一個(gè)版本例驹。
其特點(diǎn)為:
零配置,無(wú)需安裝和管理配置退唠;
儲(chǔ)存在單一磁盤(pán)文件中的一個(gè)完整的數(shù)據(jù)庫(kù)鹃锈;
數(shù)據(jù)庫(kù)文件可以在不同字節(jié)順序的機(jī)器間自由的共享;
足夠小, 大致13萬(wàn)行C代碼, 4.43M瞧预,支持?jǐn)?shù)據(jù)庫(kù)大小可至2TB屎债;
數(shù)據(jù)庫(kù)操作快;
不需要任何外部的依賴(lài)垢油。
雖然SQLite數(shù)據(jù)庫(kù)是零配置盆驹,無(wú)需安裝與管理,但為了能更好地管理SQLite中的數(shù)據(jù)庫(kù)滩愁,我們建議還是安裝躯喇,其安裝方法很簡(jiǎn)單。這里我們?cè)趙indows系統(tǒng)中安裝
安裝SQLite
在進(jìn)入SQLite下載頁(yè)面硝枉,找到Precompiled Binaries for Windows廉丽,如下圖所示:
下載紅框中的壓縮后,創(chuàng)建sqlite文件夾檀咙,并在此文件夾下解壓上面兩個(gè)壓縮文件雅倒,如下圖所示:
這里我們?cè)贓盤(pán)中創(chuàng)建sqlite文件夾璃诀,大家可以根據(jù)自身習(xí)慣來(lái)創(chuàng)建
解壓后弧可,需要將E:/sqlite添加到PATH環(huán)境變量中,如下圖所示:
在命令提示符中輸入sqlite3劣欢,如下圖所示:
好了棕诵,這樣就成功安裝SQLite了。
接下來(lái)我們通過(guò)Flask程序來(lái)演示如何使用SQLite凿将。
創(chuàng)建SQLite數(shù)據(jù)庫(kù)
創(chuàng)建Flask項(xiàng)目并在項(xiàng)目目錄下創(chuàng)建名為test.py文件校套,如下圖所示:
test.py文件作用為創(chuàng)建SQLite數(shù)據(jù)庫(kù),代碼如下所示:
import sqlite3
conn = sqlite3.connect('database.db') #建立database.db數(shù)據(jù)庫(kù)連接
conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') #執(zhí)行單條sql語(yǔ)句
conn.close() #關(guān)閉連接
創(chuàng)建SQLite數(shù)據(jù)庫(kù)很簡(jiǎn)單:建立連接——?jiǎng)?chuàng)建數(shù)據(jù)表——關(guān)閉連接牧抵。
使用sqlite3.connect()創(chuàng)建數(shù)據(jù)庫(kù)連接笛匙,當(dāng)連接的數(shù)據(jù)庫(kù)不存在時(shí),會(huì)自動(dòng)在test.py文件同級(jí)路徑下創(chuàng)建數(shù)據(jù)庫(kù)犀变,再使用execute()方法創(chuàng)建數(shù)據(jù)表妹孙,最后.close()關(guān)閉連接。
其中SQLite數(shù)據(jù)庫(kù)存儲(chǔ)的數(shù)據(jù)表值類(lèi)型有:
存儲(chǔ)類(lèi) | 描述 |
---|---|
NULL | 值是一個(gè) NULL 值获枝。 |
INTEGER | 值是一個(gè)帶符號(hào)的整數(shù)蠢正,根據(jù)值的大小存儲(chǔ)在 1、2省店、3嚣崭、4笨触、6 或 8 字節(jié)中。 |
REAL | 值是一個(gè)浮點(diǎn)值雹舀,存儲(chǔ)為 8 字節(jié)的 IEEE 浮點(diǎn)數(shù)字芦劣。 |
TEXT | 值是一個(gè)文本字符串,使用數(shù)據(jù)庫(kù)編碼(UTF-8说榆、UTF-16BE 或 UTF-16LE)存儲(chǔ)持寄。 |
BLOB | 值是一個(gè) blob 數(shù)據(jù),完全根據(jù)它的輸入存儲(chǔ)娱俺。 |
好了稍味,運(yùn)行test.py可以發(fā)現(xiàn)在項(xiàng)目目錄中創(chuàng)建了一個(gè)名為database的數(shù)據(jù)庫(kù)。
使用SQLite
首先在app.py文件中編寫(xiě)create_student視圖函數(shù)荠卷,代碼如下所示:
@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()方法將表單中的數(shù)據(jù)傳遞到視圖函數(shù)add_student中,該視圖函數(shù)代碼如下所示:
@app.route('/addstudent',methods = ['POST', 'GET'])
def add_student():
try:
#獲取請(qǐng)求中的nm油宜、add掂碱、city、pin的數(shù)據(jù)
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數(shù)據(jù)庫(kù)的連接
cur = con.cursor() #獲取游標(biāo)
cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) #添加數(shù)據(jù)慎冤,執(zhí)行單條的sql語(yǔ)句
con.commit() #提交事務(wù)
msg = "數(shù)據(jù)添加成功"
except:
con.rollback() #撤消當(dāng)前事務(wù)中所做的所有更改
msg = "操作失敗"
finally:
return render_template("result.html",msg = msg) #渲染result.html模板并傳遞msg值
con.close() #關(guān)閉數(shù)據(jù)庫(kù)連接
首先獲取請(qǐng)求中的數(shù)據(jù)疼燥,在建立與database.db數(shù)據(jù)庫(kù)連接,使用.cursor()獲取數(shù)據(jù)庫(kù)游標(biāo)蚁堤,在使用execute()方法添加數(shù)據(jù)醉者,執(zhí)行單條sql語(yǔ)句,最后提交事務(wù)披诗,當(dāng)數(shù)據(jù)添加失敗時(shí)撬即,調(diào)用rollback()方法撤消當(dāng)前事務(wù)中所做的所有更改,使用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>
操作結(jié)果 : {{ msg }}
</body>
</html>
接下來(lái)編寫(xiě)展示數(shù)據(jù)的視圖函數(shù)show_student剥槐,代碼如下所示:
@app.route('/show')
def show_student():
con = sqlite3.connect("database.db") #建立數(shù)據(jù)庫(kù)連接
con.row_factory = sqlite3.Row #設(shè)置row_factory,對(duì)查詢(xún)到的數(shù)據(jù),通過(guò)字段名獲取列數(shù)據(jù)
cur = con.cursor() #獲取游標(biāo)
cur.execute("select * from students") #執(zhí)行sql語(yǔ)句選擇數(shù)據(jù)表
rows = cur.fetchall() #獲取多條記錄數(shù)據(jù)
return render_template("show.html",rows = rows) #渲染show.html模板并傳遞rows值
建立數(shù)據(jù)庫(kù)連接并設(shè)置row_factory對(duì)象查詢(xún)到的數(shù)據(jù)通過(guò)字段名來(lái)獲取列數(shù)據(jù)宪摧,使用cursor()方法獲取數(shù)據(jù)操作游標(biāo)粒竖,再使用execute()方法執(zhí)行sql語(yǔ)句選擇數(shù)據(jù)表,使用fetchall()放過(guò)獲取多條數(shù)據(jù)几于,最后使用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>
啟動(dòng)Flask程序,訪問(wèn)http://127.0.0.1:5000/create寫(xiě)入數(shù)據(jù)孩革,如下圖所示:
點(diǎn)擊提交就會(huì)跳轉(zhuǎn)http://127.0.0.1:5000/addstudent并顯示:操作結(jié)果 : 數(shù)據(jù)添加成功岁歉。
訪問(wèn)http://127.0.0.1:5000/show,如下圖所示:
好了,F(xiàn)lask框架——Flask-SQLite數(shù)據(jù)庫(kù)就講到這里了锅移,感謝觀看熔掺,下篇文章我們學(xué)習(xí)Flask框架——Flask Sijax。
公眾號(hào):白巧克力LIN
該公眾號(hào)發(fā)布Python非剃、數(shù)據(jù)庫(kù)置逻、Linux、Flask备绽、自動(dòng)化測(cè)試券坞、Git等相關(guān)文章!