開始使用免費開始

參數化的資料庫查詢工具

隨選查詢工具可讓 LLM 依名稱或代碼搜尋貨幣,而不需載入完整清單。請使用「參數化查詢」(佔位符 ?)來避免提示詞注入,並設定列數上限,讓回應保持在可控範圍。

本練習屬於課程

Model Context Protocol(MCP)入門

檢視課程

練習說明

  • 定義一個名為 lookup_currencies() 的工具,能在 currencies 中查找 namecode 含有 prefix 的列(不區分大小寫)。
  • 使用參數化 SQL 查詢,將 prefix 插入到 ? 佔位符;使用 LIMIT 50 限制回傳列數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Add lookup_currencies(prefix): find rows where name or code contains prefix
@mcp.____()
def ____(____: str) -> str:
    """Find currencies whose code or name contains the given prefix."""
    try:
        # Use parameterized query and LIMIT 50
        cursor = conn.execute(
            "SELECT code, name FROM currencies WHERE name LIKE ? OR code LIKE ? LIMIT ____",
            (f"%{____}%", f"%{____}%")
        )
        rows = cursor.fetchall()
        return "\n".join(f"{row['code']} - {row['name']}" for row in rows)
    except sqlite3.Error as e:
        return f"Database error: {e}"

print(lookup_currencies("Euro"))
編輯並執行程式碼