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

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():
# 獲取請(qǐng)求中的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})
# 啟動(dòng)Flask應(yīng)用
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)2、創(chuàng)建知識(shí)庫,導(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)造請(qǐng)求體
payload = {
"sql": sql
}
# 發(fā)送POST請(qǐng)求
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"請(qǐng)求失敗,狀態(tài)碼:{response.status_code},{response.json()}"
}
except requests.exceptions.RequestException as e:
return {
"result": f"請(qǐng)求異常:{e}"
}
4、創(chuàng)建數(shù)據(jù)庫智能體



總結(jié)
到此這篇關(guān)于使用Dify訪問mysql數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Dify訪問mysql數(shù)據(jù)庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL與Oracle的語法區(qū)別詳細(xì)對(duì)比
Oracle和mysql的一些簡單命令對(duì)比在本文中將會(huì)涉及到很多的實(shí)例,感興趣的你不妨學(xué)習(xí)一下,就當(dāng)鞏固自己的知識(shí)了2013-03-03
MySQL系列關(guān)于NUll值的經(jīng)驗(yàn)總結(jié)分析教程
這篇文章主要為大家介紹了MySQL系列關(guān)于NUll值的一些經(jīng)驗(yàn)總結(jié)分析,關(guān)于null值的影響作用以及為什么會(huì)出現(xiàn)null值的原因等等問題的解析2021-10-10
MySQL中count(*)、count(1)和count(col)的區(qū)別匯總
count()函數(shù)是用來統(tǒng)計(jì)表中記錄的一個(gè)函數(shù),返回匹配條件的行數(shù),下面這篇文章主要給大家總結(jié)介紹了關(guān)于MySQL中count(*)、count(1)和count(col)的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2018-03-03
window環(huán)境下使用VScode連接虛擬機(jī)MySQL方法
這篇文章主要介紹了window環(huán)境下使用VScode連接虛擬機(jī)MySQL方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
MySQL數(shù)據(jù)庫事務(wù)隔離級(jí)別詳解
這篇文章主要介紹了MySQL數(shù)據(jù)庫事務(wù)隔離級(jí)別詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
Mysql 5.7.19 winx64 ZIP Archive 安裝及使用過程問題小結(jié)
本篇文章給大家介紹了mysql 5.7.19 winx64 ZIP Archive 安裝及使用過程問題小結(jié),需要的朋友可以參考下2017-07-07

