前言
在初學(xué) Flask 的時候,在數(shù)據(jù)庫連接這部分也跟每個初學(xué)者一樣。但是隨著工作中項目接手的多了,代碼寫的多了,歷練的多了也就有了自己的經(jīng)驗和技巧。在對這塊兒代碼不斷的進(jìn)行升級改造后,整理了自己在連接數(shù)據(jù)庫這部分的的一個學(xué)習(xí)經(jīng)驗,也就是我們今天分享的連接數(shù)據(jù)庫部分的打怪升級之旅。希望可以為大家在學(xué)習(xí) Python 的路上提供一些參考。
初級階段
首先安裝 Mysql 擴展包
yum install python-dev
pip install MySQL-python
建立數(shù)據(jù)庫鏈接
import MySQLdb as mysql
db=mysql.connect(user='root',passwd='123456',db='reboot',charset='utf8')
cur=db.cursor()
開啟打怪升級之路
在日常開發(fā)中,連接數(shù)據(jù)庫最多的應(yīng)用場景就是,查詢所有數(shù)據(jù)和查詢單條數(shù)據(jù)。就以查詢所有數(shù)據(jù)場景為例。
小白版本——在后端憑接表格,傳到前端渲染
cur.execute('select * from host')
str = ""
# 結(jié)果以元組嵌套的形式返回 ((id,name), (id,iname),……)
result= cur.fetchall():
# 循環(huán)父元祖,然后按照索引依次獲取到每列的值,
for c in result:
str = '<tr><td>%s</td> \
<td>%s</td> \
<td>%s</td> \
<td>%s</td> \
<td><span class="update-btn" data-id="%s">update</span></td> \
<td><span class="delete-btn" data-id="%s">delete</span></td> \
</tr>' % (c[0],c[1],c[2],c[3],c[0],c[0])
str += str
cur.close()
return jsondumps(str)
進(jìn)階階段
第一關(guān)——后端消滅 HTML 標(biāo)簽
后端:
# 執(zhí)行sql
cur.execute('select * from user')
result = cur.fetchall():
return render_template("index.html",result=result)
前端:
<table border="1px">
<tr>
<td>ID</td>
<td>user</td>
<td>passwd</td>
<td>sex</td>
<td>phone</td>
<td>操作</td>
</tr>
{% for user in result %}
<tr>
<td>{{user[0]}}</td>
<td>{{user[1]}}</td>
<td>{{user[2]}}</td>
<td>{{user[3]}}</td>
<td>{{user[5]}}</td>
</tr>
{% endfor %}
</table>
第二關(guān)——讓返回值更優(yōu)雅
users = []
# 指定需要返回的列,存入列表
fields = ['id', 'username', 'name', 'email', 'mobile']
# join將列表轉(zhuǎn)為字符串,傳入sql
sql = "SELECT %s FROM user" % ','.join(fields)
cur.execute(sql)
# 循環(huán)返回的元組
for row in cur.fetchall():
user = {}
# 利用enumerate遍歷列表,i為索引號,k為元素
# fields中列作為user字典的k,索引作為mysql返回列表的k,給字典賦值
for i, k in enumerate(fields):
user[k] = row[i]
users.append(user)
# 返回結(jié)果時列表嵌套字典,前端渲染就更優(yōu)雅了
# eg:[{'name':'wd','age':18},{'name':'pc','age':19},……]
return json.dumps({'code': 0, 'users': users})
第三關(guān)——讓代碼更簡潔
fields = ['id','username','name','email','mobile']
result= cur.fetchall()
users= [dict((k, row[i]) for i,k in enumerate(fields)) for row in result]
return json.dumps({'code':0,'users':users})
一個更高效的方式——直接將返回的嵌套元祖轉(zhuǎn)換為嵌套的字典,常用與只查詢 ID, Username 的場景
result = cur.fetchall()
# 最終結(jié)果 {1: 'ab', 2: 'bc'}
result = dict([(x['0'], x['1']) for x in result])
經(jīng)驗總結(jié)
作為一個程序員學(xué)習(xí)新的技術(shù)知識都是必須的,我們都是自己事業(yè)上無人可替的開拓者,我們都是要經(jīng)歷從入門到熟練再到精略的過程,過程雖然很痛苦不過收獲的喜悅也是別人羨慕不來的,IT 大牛 不是那么容易就練成的。希望今天的分享能夠幫助到大家。致每一位程序員