使用Dify訪問mysql數(shù)據(jù)庫詳細代碼示例

1、在本地搭建數(shù)據(jù)庫訪問的服務(wù),并使用ngrok暴露到公網(wǎng)。
#sql_tools.py
from flask import Flask, request, jsonify
import mysql.connector
# 數(shù)據(jù)庫連接配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True
}
# 初始化Flask應(yīng)用
app = Flask(__name__)
# 連接數(shù)據(jù)庫
def connect_to_database():
try:
conn = mysql.connector.connect(**config)
print("Connected to MySQL database")
return conn
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
# 執(zhí)行SQL查詢
def execute_query(conn, sql):
cursor = conn.cursor()
try:
cursor.execute(sql)
if sql.strip().lower().startswith("select"):
# 如果是查詢操作,返回結(jié)果
result = cursor.fetchall()
return result
else:
# 如果是插入、更新、刪除操作,提交事務(wù)并返回受影響的行數(shù)
conn.commit()
return cursor.rowcount
except mysql.connector.Error as err:
print(f"Error executing SQL: {err}")
return None
finally:
cursor.close()
# HTTP接口:執(zhí)行SQL
@app.route('/execute', methods=['POST'])
def execute_sql():
# 獲取請求中的SQL語句
data = request.json
if not data or 'sql' not in data:
return jsonify({"error": "SQL statement is required"}), 400
sql = data['sql']
conn = connect_to_database()
if not conn:
return jsonify({"error": "Failed to connect to database"}), 500
# 執(zhí)行SQL
result = execute_query(conn, sql)
conn.close()
if result is None:
return jsonify({"error": "Failed to execute SQL"}), 500
# 返回結(jié)果
return jsonify({"result": result})
# 啟動Flask應(yīng)用
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)2、創(chuàng)建知識庫,導(dǎo)入表結(jié)構(gòu)描述。

3、創(chuàng)建數(shù)據(jù)庫訪問工作流。

代碼執(zhí)行:
import requests
def main(sql: str) -> dict:
# 定義API的URL
url = "https://xxx.ngrok-free.app/execute"
# 構(gòu)造請求體
payload = {
"sql": sql
}
# 發(fā)送POST請求
try:
response = requests.post(url, json=payload)
# 檢查響應(yīng)狀態(tài)碼
if response.status_code == 200:
# 解析響應(yīng)數(shù)據(jù)
result = response.json()
return {
"result": f"{result}"
}
else:
return {
"result": f"請求失敗,狀態(tài)碼:{response.status_code},{response.json()}"
}
except requests.exceptions.RequestException as e:
return {
"result": f"請求異常:{e}"
}
4、創(chuàng)建數(shù)據(jù)庫智能體



總結(jié)
到此這篇關(guān)于使用Dify訪問mysql數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Dify訪問mysql數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL——修改root密碼的4種方法(以windows為例)
本文以windows為例為大家詳細介紹下MySQL修改root密碼的4種方法,大家可以可以根據(jù)的自己的情況自由選擇,希望對大家有所幫助2013-07-07
自動恢復(fù)MySQL數(shù)據(jù)庫的日志文件思路分享及解決方案
本文主要講訴如何自動恢復(fù)mysql數(shù)據(jù)庫的日志文件,喜歡的在服務(wù)器或者數(shù)據(jù)庫上直接操作的兄弟們你值得收藏下!2014-08-08

