看了彭彭老師的教學課程後,我開始思考要怎麼用mysql實現。
我想實現一個辦公系統,假設使用者輸入一個關鍵字,例如printer,那系統會將會回傳負責團隊或負責人,若是沒有資料則傳回查無相關資料
我的MYSQL資料庫
使用者輸入一個關鍵字,後端會去和ITEM欄位底比較有沒有相同或類似的資料。若有則回傳TYPE和Explantion的資料。

假設使用者輸入ITEM欄位沒有的餅乾


假設使用者輸入ITEM欄位有的money


python flask腳本
#--------------python Sql資料庫-----------------------
import mysql.connector #載入MSQL
connection = mysql.connector.connect(host="****",
port="****",
user="****",
password="****",
auth_plugin="mysql_native_password",
database="TESTDB")
#--------------#--------------python flask網站後端-----------------------
from flask import * #import flask全部模組
app = Flask(
__name__,
static_folder= "static", #靜態檔案的資料夾名稱
static_url_path ="/" #靜態檔案對應的網址路徑
)
# #處理路由
# 首頁index.html
@app.route("/")
def index():
return render_template("index.html")
@app.route("/search")
def search():
#重前端接收資料
#接收GET方法的 Query String保存到變數Name
Name= request.args.get("n","")
#連線資料庫
cursor =connection.cursor()
#篩選資料庫中Item欄位的部分有沒有和變數Name符合或相似
cursor.execute("SELECT * FROM Testtable WHERE Item LIKE %s",('%'+Name+'%',))
# 根據接收到的資料跟資料庫作互動,將資料保存到result
# 如果USER的輸入和MYSSQL中Item欄位相同的話,將資料保存到result
result = cursor.fetchone()
NODATA ="查無相關資料"
#如果找不到對應資料在頁面顯示沒有資料
if result == None:
return render_template("result.html",result1= str(NODATA),result2= str(NODATA),result3= str(NODATA))
#如果找到對應資料將在頁面顯示MYSQL的TYPE和Explantion欄位內的資料
Type = result[1]
Name = result[2]
Explantion = result[3]
return render_template("result.html",result1= str(Name),result2= str(Type),result3= str(Explantion))
if __name__=="__main__":
app.run(host="127.0.0.1",port=5000,debug=True)



index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>負責團隊搜尋</title>
</head>
<body>
<h1>負責團隊搜尋</h1>
<form action="/search">
輸入:<input type="text" name="n" />
<br/>
<button>搜尋</button>
</form>
</body>
</html>

result.com
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>搜尋結果</title>
</head>
<body>
<h1>搜尋結果</h1>
<div>你查詢的資料: {{result1}}</br>
負責團隊: {{result2}}</br>
詳細說明: {{result3}}</div>
詳細說明: {{result3}}</div>
</body>
</html>

這邊花好多時間在找要怎麼抓數據,因為不知道要如何結合sql和python的變數來找數據。
後來找到下面這篇,除了可以設定成變數外,還有%s或%a之類抓相似的條件。]
#篩選資料庫中Item欄位的部分有沒有和變數Name符合或相似
cursor.execute("SELECT * FROM table名 WHERE 欄位 LIKE %s",('%'+變數+'%',))
輸入prin也能導向printer,找到答案
以下可以參考這一篇 SQL LIKE 操作符


最後想實現用外網連到網頁,把host改成”0.0.0.0″聽說可以實現,但似乎因為防火牆的關係,我怎麼連都無法成功。而且也覺得不是很安全,所以考慮可不可以設白名單來實現特定使用者的連線。
if __name__=="__main__":
app.run(host="0.0.0.0",port=5000,debug=True)