# 建立與設定資料庫

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

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

MaiAgent 支援兩種資料庫類型：

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

## 建立資料庫 <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>」。頁面分為兩個頁籤：**MaiAgent 資料庫**與**外部資料庫**。

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

<figure><img src="/files/E4ETxDakHOPb8eazwvm5" alt="資料庫管理頁面"><figcaption><p>資料庫管理頁面，顯示 MaiAgent 資料庫列表</p></figcaption></figure>

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

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

選擇您要建立的資料庫類型，點擊對應的卡片：

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

<figure><img src="/files/ylNv54jCIIR5gvYzMR16" 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="/files/HRs9S0Jju4lZX017CUGg" alt="MaiAgent 資料庫設定"><figcaption><p>步驟二：MaiAgent 資料庫設定畫面</p></figcaption></figure>

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

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

連線字串格式如下：

```
PostgreSQL:   postgresql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
MySQL:        mysql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
MSSQL:        mssql+pymssql://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
Oracle:       oracle+cx_oracle://使用者名稱:密碼@主機位址:連接埠/資料庫名稱
```

{% hint style="danger" %}
請務必確認連線字串格式正確，並包含必要的連線資訊。需要確保資料庫 URL 是可以被 MaiAgent 服務訪問的。
{% endhint %}

<figure><img src="/files/seAGbvVXTv0TtIzrJ9kW" alt="外部資料庫設定"><figcaption><p>步驟二：外部資料庫（PostgreSQL）設定畫面</p></figcaption></figure>

填寫連線字串後，建議點擊「<mark style="color:blue;">測試連線</mark>」按鈕來驗證連線是否正常：

* **連線成功**：代表 MaiAgent 可以正常存取您的資料庫
* **連線失敗**：請檢查連線字串格式、網路連通性，以及資料庫是否允許外部連線

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

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

最後一步是設定哪些群組可以存取這個資料庫。使用左右穿梭元件，將需要授權的群組從左側移至右側即可。

{% hint style="info" %}
若暫時不需要設定群組權限，可以直接跳過此步驟，之後再從資料庫設定頁面進行調整。
{% endhint %}

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

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

{% hint style="info" %}
建立完成後，別忘了將資料庫**關聯至 AI 助理**，AI 助理才能使用這個資料庫進行查詢。請參考：[關聯 AI 助理與群組權限](/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>」按鈕。

<figure><img src="/files/vSgNU3S21nri9ADJFLqG" 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 格式資料檔案            |

上傳後，系統會在背景自動解析檔案結構並建立資料表。每張資料表會顯示處理狀態：

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

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

* [x] 第一列（Row）必須為**欄位名稱**
* [x] 每個欄位的**資料型態**應保持一致（例如：價格欄位都是數字）
* [x] 避免**合併儲存格**
* [x] 避免**重複的欄位名稱**
* [x] Excel 檔案中，每個工作表（Sheet）只能包含**一個表格**
* [x] 建議在欄位名稱後標註資料格式，例如：`價格(int)`、`日期(datetime)`

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

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

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

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

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

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

**外部資料庫**：在「<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="/files/Jl5qS2saDtf6SLNTDKis" alt="資料庫設定頁面"><figcaption><p>資料庫設定頁面：基本資訊頁籤</p></figcaption></figure>

設定頁面包含以下頁籤：

| 頁籤       | 說明                 | 適用類型       |
| -------- | ------------------ | ---------- |
| 基本資訊     | 編輯名稱、描述、啟用狀態、連線字串  | 全部         |
| 表格管理     | 上傳檔案、管理資料表與欄位描述    | 僅 MaiAgent |
| 關聯 AI 助理 | 指定哪些 AI 助理可以使用此資料庫 | 全部         |
| 角色權限     | 設定群組的存取權限          | 全部         |

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

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

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

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

* **MaiAgent 資料庫**：刪除後，所有透過上傳檔案建立的資料表都會被一併移除
* **外部資料庫**：僅移除 MaiAgent 中的連線設定，不會影響原始資料庫中的資料
  {% endhint %}


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

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

The question should be specific, self-contained, and written in natural language.
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.
