> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/build/database/create-database.md).

# 建立與設定資料庫

建立資料庫問答（Text-to-SQL／Text2SQL）：上傳檔案建立資料表、連接外部資料庫，以及設定欄位描述，讓 Agent 以自然語言查詢資料。

MaiAgent 的**資料庫管理**功能讓您可以在平台上集中管理 Agent 所使用的資料庫連線。搭配 Text to SQL 功能，Agent 就能透過自然語言直接查詢資料庫中的資料。

{% hint style="info" %}
關於 Text to SQL 的概念介紹，請參考：[Text to SQL 功能](/build/database/text2sql.md)
{% endhint %}

MaiAgent 支援兩種資料庫類型：

* **MaiAgent 資料庫**：上傳 Excel / CSV / JSON 檔案，系統自動建立資料表。適合沒有自建資料庫的使用者
* **外部資料庫**：連接既有的 PostgreSQL、MySQL、SQL Server（MSSQL）、Oracle 或 SynxDB 資料庫

## 網路前置（外部資料庫） <a href="#network-prerequisites" id="network-prerequisites"></a>

連接外部資料庫之前，請先和貴單位的 IT 或資料庫管理員確認以下事項。只使用 MaiAgent 資料庫（上傳試算表）時，不需要這些設定。

* [ ] **允許 MaiAgent 連入**：連線由 MaiAgent 主動連到您的資料庫（按「<mark style="color:blue;">測試連線</mark>」時與 Agent 每次查詢時），資料庫不需要主動連到 MaiAgent。
* [ ] **開放連接埠**：預設為 PostgreSQL 5432、MySQL 3306、SQL Server 1433、Oracle 1521、SynxDB 5432（依部署設定）；改過埠號時，以「<mark style="color:blue;">連線字串</mark>」中 `主機位址:連接埠` 的埠號為準。
* [ ] **MaiAgent 雲端服務**：資料庫有防火牆或安全群組時，把 MaiAgent 的對外 IP 加入白名單（請洽 MaiAgent 窗口索取），只開放上述連接埠。
* [ ] **地端／私有雲部署**：確認 MaiAgent 主機與資料庫主機之間的網段與連接埠可以互通即可，資料庫不需要開放到網際網路。
* [ ] **使用唯讀帳號**：為 MaiAgent 建立專用的唯讀帳號，只授予 Agent 需要的資料表；含個資等敏感欄位的資料表，可另建只含必要欄位的檢視表（View）再授權。「<mark style="color:blue;">指定資料表</mark>」只縮小 Agent 參考的範圍，真正讀得到哪些資料，仍由這個帳號的權限決定。

平台如何擋下寫入語法、各資料庫的唯讀保護程度，以及網路需求的完整說明，見技術人員手冊 [Text to SQL：唯讀保護](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql#read-only) 與 [網路需求](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql#network)。

## 建立資料庫 <a href="#create-database" id="create-database"></a>

### 1. 進入資料庫管理頁面 <a href="#enter-database-management-page" id="enter-database-management-page"></a>

從左側導航欄進入「<mark style="color:blue;">AI 功能</mark>」區塊，點擊「<mark style="color:blue;">資料庫</mark>」。頁面分為兩個頁籤：<mark style="color:blue;">MaiAgent 資料庫</mark>與<mark style="color:blue;">外部資料庫</mark>。

點選右上角的「<mark style="color:blue;">新增資料庫</mark>」按鈕開始建立。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-1679e98bd1aac4aaa4518e438af0f88ac67c34e7%2Fdatabase-list-page.png?alt=media" alt="資料庫管理頁面"><figcaption><p>資料庫管理頁面，顯示 MaiAgent 資料庫列表</p></figcaption></figure>

{% hint style="info" %}
若按鈕為灰色無法點擊，代表您的角色尚未被授予建立資料庫的權限。請聯繫組織管理員設定權限。
{% endhint %}

### 2. 選擇資料庫類型 <a href="#select-database-type" id="select-database-type"></a>

選擇您要建立的資料庫類型，點擊對應的卡片後按「<mark style="color:blue;">下一步</mark>」：

* **MaiAgent 資料庫**：適合上傳試算表檔案，不需要連線字串
* **PostgreSQL / MySQL / SQL Server / Oracle / SynxDB**：連接企業既有的外部資料庫

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-7bfa7cfc7a933807d14941d090f30a8442c0e3af%2Fdatabase-create-select-type.png?alt=media" alt="選擇資料庫類型"><figcaption><p>步驟一：選擇資料庫類型</p></figcaption></figure>

### 3. 填寫基本資訊 <a href="#fill-in-basic-info" id="fill-in-basic-info"></a>

#### MaiAgent 資料庫 <a href="#maiagent-database-info" id="maiagent-database-info"></a>

| 欄位    | 必填 | 說明              |
| ----- | -- | --------------- |
| 資料庫名稱 | 是  | 例如「2024 年度銷售資料」 |
| 說明    | 否  | 補充說明資料庫的用途或內容   |

{% hint style="info" %}
MaiAgent 資料庫不需要輸入連線字串，系統會自動處理資料儲存。建立完成後再上傳試算表檔案即可。
{% endhint %}

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-87d0a0885bc2b8454421703e90225a019c1e2b57%2Fdatabase-create-info-maiagent.png?alt=media" alt="MaiAgent 資料庫設定"><figcaption><p>步驟二：MaiAgent 資料庫設定畫面</p></figcaption></figure>

#### 外部資料庫 <a href="#external-database-info" id="external-database-info"></a>

| 欄位    | 必填 | 說明                     |
| ----- | -- | ---------------------- |
| 資料庫名稱 | 是  | 例如「企業 ERP 資料庫」         |
| 說明    | 否  | 補充說明資料庫的用途或內容          |
| 連線字串  | 是  | 資料庫的連線 URL             |
| 指定資料表 | 否  | 限制 Agent 可查詢的資料表，以逗號分隔 |

連線字串格式如下（欄位下方也會顯示所選類型的格式）：

```
PostgreSQL:   postgresql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
MySQL:        mysql+pymysql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
SQL Server:   mssql+pyodbc://使用者名稱:密碼@主機位址:連接埠/資料庫名稱?driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes&Encrypt=no
Oracle:       oracle+oracledb://使用者名稱:密碼@主機位址:連接埠/?service_name=服務名稱
SynxDB:       postgresql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
```

{% hint style="danger" %}
請務必確認連線字串格式正確，並包含必要的連線資訊。開頭必須與上方格式一致，否則會顯示「連線字串格式不正確」而無法進入下一步。也請確認資料庫已允許 MaiAgent 連入，請參考 [網路前置](#network-prerequisites)。
{% endhint %}

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-6158a998800e16ec360cd66dc1d0203786acdcf4%2Fdatabase-create-info-external.png?alt=media" alt="外部資料庫設定"><figcaption><p>步驟二：外部資料庫（PostgreSQL）設定畫面</p></figcaption></figure>

填寫連線字串後，建議點擊「<mark style="color:blue;">測試連線</mark>」按鈕來驗證連線是否正常（也可以跳過測試直接儲存）：

* **連線成功**：代表 MaiAgent 可以正常存取您的資料庫
* **連線失敗**：請檢查連線字串格式、帳號密碼，以及防火牆、白名單與連接埠是否已依 [網路前置](#network-prerequisites) 開放

若您的資料庫包含大量資料表，可以在「<mark style="color:blue;">指定資料表</mark>」欄位中輸入要開放的資料表名稱（例如 `customers, orders, products`），以提升查詢效率及安全性。留空表示查詢所有資料表。

### 4. 設定角色權限 <a href="#configure-group-permission" id="configure-group-permission"></a>

最後一步是設定哪些角色可以存取這個資料庫。在「<mark style="color:blue;">快速選擇權限範圍</mark>」中選擇其一：

* <mark style="color:blue;">全部角色</mark>：允許組織內所有角色的成員使用此資料庫
* <mark style="color:blue;">排除預設角色</mark>：僅允許自訂角色使用，排除預設角色
* <mark style="color:blue;">自訂選擇角色</mark>：手動選擇特定角色，將需要授權的角色從「<mark style="color:blue;">可選角色</mark>」移至「<mark style="color:blue;">已選角色</mark>」

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-370933d45e5081799639a1b310f3f3ae875936a2%2Fdatabase-create-role-permission.png?alt=media" alt="設定角色權限"><figcaption><p>步驟三：快速選擇權限範圍</p></figcaption></figure>

{% hint style="info" %}
若暫時不需要設定角色權限，可以直接跳過此步驟，之後再從資料庫設定頁面的「<mark style="color:blue;">角色權限</mark>」頁籤進行調整。
{% endhint %}

### 5. 完成建立 <a href="#complete-creation" id="complete-creation"></a>

確認所有設定後，點擊「<mark style="color:blue;">建立資料庫</mark>」（MaiAgent 資料庫）或「<mark style="color:blue;">儲存</mark>」（外部資料庫）按鈕。建立成功後會進入資料庫設定頁面，可以進行後續操作。

{% hint style="warning" %}
新建立的資料庫預設為**停用**狀態。請在「<mark style="color:blue;">基本資訊</mark>」頁籤開啟「<mark style="color:blue;">啟用資料庫</mark>」並儲存，或在資料庫列表中切換「<mark style="color:blue;">啟用</mark>」開關，Agent 才會在 Text to SQL 查詢中使用此資料庫。
{% endhint %}

{% hint style="info" %}
建立完成後，別忘了將資料庫**關聯至 Agent**，Agent 才能使用這個資料庫進行查詢。請參考：[關聯 Agent 與群組權限](/build/database/link-chatbots-groups.md)
{% endhint %}

## 上傳檔案建立資料表（MaiAgent 資料庫） <a href="#upload-file-to-create-table" id="upload-file-to-create-table"></a>

建立 MaiAgent 資料庫後，進入設定頁面切換至「<mark style="color:blue;">表格管理</mark>」頁籤，點擊「<mark style="color:blue;">上傳表格檔案</mark>」按鈕，選擇檔案或拖曳至上傳區後點擊「<mark style="color:blue;">上傳</mark>」。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-20335fe758b8e0f9dbd3fd5f1bb89d70b698624a%2Fdatabase-config-table-management.png?alt=media" alt="表格管理頁籤"><figcaption><p>表格管理頁籤，資料表依來源檔案分組顯示</p></figcaption></figure>

### 支援的檔案格式 <a href="#supported-file-formats" id="supported-file-formats"></a>

| 格式    | 副檔名              | 說明                     |
| ----- | ---------------- | ---------------------- |
| Excel | `.xlsx`、`.xls`   | 每個工作表（Sheet）會各自建立一張資料表 |
| CSV   | `.csv`           | 逗號分隔值檔案                |
| JSON  | `.json`、`.jsonl` | JSON 格式資料檔案            |

上傳後，系統會在背景自動解析檔案結構並建立資料表。資料表會依來源檔案分組列出，並顯示處理狀態：

| 狀態   | 說明                      |
| ---- | ----------------------- |
| 待處理  | 檔案已上傳，等待系統處理            |
| 處理中  | 系統正在解析檔案並建立資料表          |
| 成功   | 資料表建立完成，Agent 可以查詢      |
| 失敗   | 建立過程發生錯誤，可將滑鼠移至錯誤圖示查看原因 |
| 刪除中  | 正在背景移除資料表               |
| 刪除失敗 | 移除未完成，可再刪一次             |

來源檔案名稱下方標示 「<mark style="color:blue;">來自知識庫</mark>」 的資料表，不是在這裡上傳的，而是知識庫上傳結構化檔案時[改用資料庫](/build/knowledge-base/km.md#table-row-limit)同步過來的；同一份檔案在知識庫與資料庫各有一份，刪除其中一邊不會影響另一邊。

### 資料表名稱與重複上傳 <a href="#table-naming-and-reupload" id="table-naming-and-reupload"></a>

* 資料表名稱由系統產生：`table_<檔名>_<10 碼雜湊>`。檔名取上傳檔案的名稱去掉副檔名、只保留中英文、數字與底線，最長 45 個字元；雜湊由這次上傳的檔案 ID 與工作表名稱算出。例如上傳 `2024 銷售.xlsx` 的「Q1」工作表，會得到 `table_2024銷售_` 加 10 碼雜湊的名稱。Agent 查詢時看的是這個名稱，建議在 [表格描述](#edit-column-description) 寫明它是哪份檔案的哪個工作表。
* Excel 的每個工作表各建一張資料表，建立成功的資料表會自動加入資料庫的 <mark style="color:blue;">指定資料表</mark>。
* **再次上傳同名檔案不會覆蓋**：每次上傳都是新的檔案 ID，雜湊不同，所以會建立另一組資料表，舊的資料表與欄位描述原樣保留，Agent 會同時看到兩組。要更新資料，請先在 <mark style="color:blue;">表格管理</mark> 刪除舊資料表（或整個來源檔案），再上傳新檔；刪除後欄位描述不會保留，請先記下。
* 從知識庫同步過來的資料表（標示 <mark style="color:blue;">來自知識庫</mark>）命名規則相同，刪除時兩邊互不影響。

### 檔案格式注意事項 <a href="#file-format-notes" id="file-format-notes"></a>

* [x] 第一列（Row）必須為**欄位名稱**
* [x] 每個欄位的**資料型態**應保持一致（例如：價格欄位都是數字）
* [x] 避免**合併儲存格**
* [x] 避免**重複的欄位名稱**
* [x] Excel 檔案中，每個工作表（Sheet）只能包含**一個表格**

{% hint style="warning" %}
若資料表建立失敗，常見原因包括：檔案格式不正確或損毀、欄位名稱包含特殊字元、欄位名稱重複、同一欄位中的資料型態不一致。
{% endhint %}

## 編輯欄位描述 <a href="#edit-column-description" id="edit-column-description"></a>

欄位描述是提升 Text to SQL 查詢準確度的**關鍵設定**。Agent 會參考欄位描述來理解資料的含義，從而產生更精確的 SQL 查詢。

例如，您的資料表有一個欄位叫 `status`，Agent 可能不知道它代表什麼。但如果加上描述「訂單狀態，可能的值為：pending（待處理）、completed（已完成）、cancelled（已取消）」，Agent 就能正確理解這個欄位的含義。

### 如何編輯 <a href="#how-to-edit" id="how-to-edit"></a>

**MaiAgent 資料庫**：在「<mark style="color:blue;">表格管理</mark>」頁籤中，點擊資料表操作欄的「<mark style="color:blue;">編輯</mark>」圖示，開啟「<mark style="color:blue;">編輯表格資訊</mark>」視窗，即可填寫「<mark style="color:blue;">表格描述</mark>」與每個欄位的「<mark style="color:blue;">欄位描述</mark>」，完成後點擊「<mark style="color:blue;">儲存</mark>」。視窗中會顯示填寫進度（例如「已設定 3 / 10 個欄位」）。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-55bbc387eb441d873faf95addb67a70ecba7ce0c%2Fdatabase-edit-table-info.png?alt=media" alt="編輯表格資訊視窗"><figcaption><p>編輯表格資訊：填寫表格描述與欄位描述</p></figcaption></figure>

**外部資料庫**：在「<mark style="color:blue;">基本資訊</mark>」頁籤下方的「<mark style="color:blue;">資料表結構描述</mark>」區塊，點擊「<mark style="color:blue;">新增表格</mark>」，填寫「<mark style="color:blue;">表格名稱</mark>」與「<mark style="color:blue;">欄位與用途說明</mark>」，完成後點擊「<mark style="color:blue;">儲存</mark>」。

### 撰寫建議 <a href="#writing-suggestions" id="writing-suggestions"></a>

{% hint style="info" %}
好的欄位描述能顯著提升 AI 查詢的準確度：
{% endhint %}

| 欄位名稱       | 較差的描述 | 較好的描述                                                |
| ---------- | ----- | ---------------------------------------------------- |
| `amt`      | 金額    | 訂單總金額（新台幣），包含稅金和運費                                   |
| `cust_lvl` | 等級    | 客戶等級，A 級為年消費超過 100 萬的 VIP 客戶，B 級為年消費 10-100 萬，C 級為其他 |
| `reg`      | 區域    | 客戶所在地理區域，可能的值為：北部、中部、南部、東部、離島                        |

## 管理既有資料庫 <a href="#manage-existing-databases" id="manage-existing-databases"></a>

### 編輯資料庫 <a href="#edit-database" id="edit-database"></a>

在資料庫列表中，點擊操作欄的「<mark style="color:blue;">編輯</mark>」圖示即可進入設定頁面。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-4730481d7efc94106f51933b1d9399496e2a39b8%2Fdatabase-config-basic-info.png?alt=media" alt="資料庫設定頁面"><figcaption><p>資料庫設定頁面：基本資訊頁籤</p></figcaption></figure>

設定頁面包含以下頁籤：

| 頁籤                                        | 說明                                       | 適用類型       |
| ----------------------------------------- | ---------------------------------------- | ---------- |
| 基本資訊                                      | 編輯名稱、說明、啟用狀態；外部資料庫另可變更連線字串、指定資料表與資料表結構描述 | 全部         |
| 表格管理                                      | 上傳檔案、管理資料表與欄位描述                          | 僅 MaiAgent |
| <mark style="color:blue;">關聯 AI 助理</mark> | 指定哪些 Agent 可以使用此資料庫                      | 全部         |
| 角色權限                                      | 設定角色的存取權限                                | 全部         |

{% hint style="info" %}
基於安全考量，外部資料庫的連線字串會以遮罩顯示密碼。若要修改，點擊「<mark style="color:blue;">變更</mark>」後輸入新的完整連線字串。
{% endhint %}

### 啟用 / 停用 <a href="#enable-disable" id="enable-disable"></a>

在資料庫列表中，透過「啟用」開關可以快速切換狀態。停用後 Agent 將暫時無法查詢此資料庫，但設定和資料會保留。

### 刪除資料庫 <a href="#delete-database" id="delete-database"></a>

在資料庫列表的操作欄點 <mark style="color:blue;">刪除</mark>，會開啟 「<mark style="color:blue;">刪除資料庫</mark>」 確認視窗，顯示「確定要刪除「資料庫名稱」嗎？」。MaiAgent 資料庫的視窗另有 「<mark style="color:blue;">刪除前請留意</mark>」 提醒：此資料庫的表格可能來自知識庫的檔案同步，希望完整清除時，建議也到知識庫檢查是否有需要一併刪除的檔案；刪除後此資料庫及其所有表格資料將無法恢復。外部資料庫則提示「刪除後，此資料庫連線設定將無法恢復」。按 <mark style="color:blue;">確認刪除</mark> 後執行。

{% hint style="danger" %}
刪除資料庫是不可逆的操作。

* **MaiAgent 資料庫**：刪除後，所有透過上傳檔案建立的資料表都會被一併移除；從知識庫同步來的資料表，其知識庫端的檔案仍會保留
* **外部資料庫**：僅移除 MaiAgent 中的連線設定，不會影響原始資料庫中的資料
  {% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/build/database/create-database.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
