環境 python 3.9
安裝模組
- pip install flask
- pip install pymysql
- pip install mariadb
- pip install json
複製代碼
建立資料庫flask_tw
建立資料表
Id, FristName, LastName, Addr, City
程式碼
- import pymysql
- from flask import Flask
- pymysql.install_as_MySQLdb() # Install MySQL driver
- import json
- import mariadb
- config = {
- 'host': '127.0.0.1',
- 'port': 3306,
- 'user': 'flask_tw',
- 'password': 'password',
- 'database': 'flask_tw'
- }
- app = Flask(__name__)
- @app.route("/")
- def index():
- return "connect success!!"
- @app.route('/api/people', methods=['GET'])
- def dbtest():
- # connection for MariaDB
- conn = mariadb.connect(**config)
- # create a connection cursor
- cur = conn.cursor()
- # execute a SQL statement
- cur.execute("select * from people")
- # serialize results into JSON
- row_headers=[x[0] for x in cur.description]
- rv = cur.fetchall()
- json_data=[]
- for result in rv:
- json_data.append(dict(zip(row_headers,result)))
- # return the results!
- return json.dumps(json_data)
- if __name__ == '__main__':
- app.run()
複製代碼
新增資料 加入
- @app.route("/insert")
- def insert():
- insertStatement = "INSERT INTO people (id, LastName, FirstName,Address,City) VALUES (5,'woff2','lin2','hsinchu2','city2')";
- conn = mariadb.connect(**config)
- # create a connection cursor
- cur = conn.cursor()
- cur.execute(insertStatement)
- return ("Successfully added entry to database")
複製代碼
如果我要使用取得欄位名時會出現錯誤
- records = cursor.fetchall()
- for row in records:
- val1 = row["columnName1"], )
- val2 = row["columnName2"])
- val3 = row["columnName3"])
複製代碼如果您嘗試直接使用列名獲取數據,您將收到TypeError: tuple indices must be integers or slices, not str。
要使用列名從我的 MySQL 表中選擇記錄,我們只需要更改遊標建立方式。將標準遊標建立方式替換為以下程式碼,即可使用列名從我的 MySQL 表中取得記錄。 在 conn = mariadb.connect(**config) 下增加一行 - cursor = conn.cursor(dictionary=True)
複製代碼
為什麼要設定dictionary=True?因為 MySQLCursorDict 建立一個遊標,該遊標將行作為字典返回,因此我們可以使用列名進行存取(此處列名是字典的鍵)
文章出處: NetYea 網頁設計
https://hackernoon.com/getting-s ... -and-flask-pa1i3ya3
https://pynative.com/python-mysql-select-query-to-fetch-data/
|