> ## Documentation Index
> Fetch the complete documentation index at: https://ikun.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# SQL

**SQLTools** 允许代理运行 SQL 查询并与数据库进行交互。

## 先决条件

以下示例需要 `sqlalchemy` 库和数据库 URL。

```shell theme={null}
pip install -U sqlalchemy
```

您还需要安装要使用的特定数据库的相应 Python 适配器。

### PostgreSQL

对于 PostgreSQL，您可以安装 `psycopg2-binary` 适配器：

```shell theme={null}
pip install -U psycopg2-binary
```

### MySQL

对于 MySQL，您可以安装 `mysqlclient` 适配器：

```shell theme={null}
pip install -U mysqlclient
```

`mysqlclient` 适配器可能需要额外的系统级依赖。请查阅[官方安装指南](https://github.com/PyMySQL/mysqlclient/blob/main/README.md#install)了解更多详情。

您还需要一个数据库。以下示例使用在 Docker 容器中运行的 Postgres 数据库。

```shell theme={null}
 docker run -d \
  -e POSTGRES_DB=ai \
  -e POSTGRES_USER=ai \
  -e POSTGRES_PASSWORD=ai \
  -e PGDATA=/var/lib/postgresql/data/pgdata \
  -v pgvolume:/var/lib/postgresql/data \
  -p 5532:5432 \
  --name pgvector \
  agno/pgvector:16
```

## 示例

以下代理将运行一个 SQL 查询来列出数据库中的所有表，并描述其中一个表的内容。

```python cookbook/tools/sql_tools.py theme={null}
from agno.agent import Agent
from agno.tools.sql import SQLTools

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

agent = Agent(tools=[SQLTools(db_url=db_url)])
agent.print_response("List the tables in the database. Tell me about contents of one of the tables", markdown=True)
```

## Toolkit 参数

| 参数               | 类型               | 默认值    | 描述                    |
| ---------------- | ---------------- | ------ | --------------------- |
| `db_url`         | `str`            | -      | 用于连接数据库的 URL。         |
| `db_engine`      | `Engine`         | -      | 用于连接和操作的数据库引擎。        |
| `user`           | `str`            | -      | 数据库认证的用户名。            |
| `password`       | `str`            | -      | 数据库认证的密码。             |
| `host`           | `str`            | -      | 数据库服务器的主机名或 IP 地址。    |
| `port`           | `int`            | -      | 数据库服务器正在监听的端口号。       |
| `schema`         | `str`            | -      | 要使用的数据库中的特定 schema。   |
| `dialect`        | `str`            | -      | 数据库使用的 SQL 方言。        |
| `tables`         | `Dict[str, Any]` | -      | 一个将表名映射到其各自元数据或结构的字典。 |
| `list_tables`    | `bool`           | `True` | 启用列出数据库中所有表的功能。       |
| `describe_table` | `bool`           | `True` | 启用描述特定表模式的功能。         |
| `run_sql_query`  | `bool`           | `True` | 启用直接执行 SQL 查询的功能。     |

## Toolkit 函数

| 函数               | 描述           |
| ---------------- | ------------ |
| `list_tables`    | 列出数据库中的所有表。  |
| `describe_table` | 描述特定表的模式。    |
| `run_sql_query`  | 直接执行 SQL 查询。 |

## 开发者资源

* 查看 [Tools](https://github.com/agno-agi/agno/blob/main/libs/agno/agno/tools/sql.py)
* 查看 [Cookbook](https://github.com/agno-agi/agno/blob/main/cookbook/tools/sql_tools.py)
