環境準備:python
環境的問題就到這裏,百度一下各類教程,這裏就不羅嗦mysql
新建一個sqllite數據庫:web
新建記事本,將記事本名字改成:info.dbsql
使用pycharm打開info.db,建立student表,包含id,name,age。數據庫
使用pycharm新建一個flask項目json
將info.db移動至webserver項目文件夾下flask
如今開始代碼部分。app
對student表進行插入操做工具
對student表進行查詢操做post
啓動webserver項目:python webserver.py 成功後使用postman進行測試
1.插入數據:
根據路由,使用 127.0.0.1:5000/add 的post方法進行新增操做
須要傳遞的參數爲json格式{「id」:」7」,」name」:」3」,」age」:」23」},點擊send便可,而後查看數據庫中是否成功插入數據
數據庫中數據:
2.查詢數據
使用get方式直接在url中輸入地址便可,輸入地址爲ID=6的學生信息,返回的數據也是json格式的數據。
源碼以下:
1 # coding=utf-8 2 import sqlite3 3 from flask import Flask, jsonify,request 4 5 # 防止中文亂碼 6 import sys 7 reload(sys) 8 sys.setdefaultencoding("utf-8") 9 10 app = Flask(__name__) 11 12 13 @app.route('/add',methods=['POST']) 14 def add_student(): 15 # 鏈接數據庫 16 conn = sqlite3.connect('info.db') 17 cur = conn.cursor() 18 19 student = { 20 'id': request.json['id'], 21 'name': request.json['name'], 22 'age': request.json['age'] 23 } 24 25 sql='insert into student values(%s,%s,%s)' %(student['id'],student['name'],student['age']) 26 27 # 執行sql語句 28 cur.execute(sql) 29 conn.commit() 30 print sql 31 32 # 關閉鏈接 33 conn.close() 34 return u"插入成功" 35 36 37 @app.route('/<int:id>', methods=['GET']) 38 def query(id): 39 40 # 鏈接數據庫 41 conn = sqlite3.connect('info.db') 42 cur = conn.cursor() 43 # 執行sql語句 44 sql = "select id,name,age from student where id = " + str(id) 45 cur.execute(sql) 46 result = cur.fetchall() 47 print sql 48 # 關閉鏈接 49 conn.close() 50 return jsonify( 51 { 52 'id': result[0][0], 53 'name': result[0][1], 54 'age': result[0][2], 55 }) 56 57 58 @app.errorhandler(404) 59 def page_not_found(e): 60 res = jsonify({'error': 'not found'}) 61 res.status_code = 404 62 return res 63 64 65 if __name__ == '__main__': 66 app.run(host='0.0.0.0')