> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-commands.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# 34.3. 執行 SQL 命令 \#

### 34.3. 執行 SQL 命令 [#](#ecpg-commands) <a href="#ecpg-commands" id="ecpg-commands"></a>

[34.3.1. 執行 SQL 陳述式](#ecpg-executing)

[34.3.2. 使用游標](#ecpg-cursors)

[34.3.3. 管理交易](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-commands/ecpg-transactions.md#ecpg-transactions)

[34.3.4. 預備陳述式](#ecpg-prepared)

任何 SQL 命令都可以在嵌入式 SQL 應用程式中執行。以下是幾個執行方式的範例。

#### 34.3.1. 執行 SQL 陳述式 [#](#ecpg-executing) <a href="#ecpg-executing" id="ecpg-executing"></a>

建立資料表：

```

EXEC SQL CREATE TABLE foo (number integer, ascii char(16));
EXEC SQL CREATE UNIQUE INDEX num1 ON foo(number);
EXEC SQL COMMIT;
```

插入資料列：

```

EXEC SQL INSERT INTO foo (number, ascii) VALUES (9999, 'doodad');
EXEC SQL COMMIT;
```

刪除資料列：

```

EXEC SQL DELETE FROM foo WHERE number = 9999;
EXEC SQL COMMIT;
```

更新：

```

EXEC SQL UPDATE foo
    SET ascii = 'foobar'
    WHERE number = 9999;
EXEC SQL COMMIT;
```

傳回單一結果資料列的 `SELECT` 陳述式，也可以直接使用 `EXEC SQL` 執行。若要處理含有多個資料列的結果集，應用程式必須使用游標；請參閱下方的[第 34.3.2 節](#ecpg-cursors)。（作為特例，應用程式可以一次將多個資料列擷取到陣列主機變數中；請參閱[第 34.4.4.3.1 節](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-variables/ecpg-variables-type-mapping/ecpg-variables-nonprimitive-c.md#ecpg-variables-arrays)。）

單列查詢：

```

EXEC SQL SELECT foo INTO :FooBar FROM table1 WHERE ascii = 'doodad';
```

此外，也可以使用 `SHOW` 命令取得設定參數的值：

```

EXEC SQL SHOW search_path INTO :var;
```

形式為 `:something` 的語彙單元就是*主機變數*，也就是說，它們參照 C 程式中的變數。[第 34.4 節](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-variables.md)會說明主機變數。

#### 34.3.2. 使用游標 [#](#ecpg-cursors) <a href="#ecpg-cursors" id="ecpg-cursors"></a>

若要取得含有多個資料列的結果集，應用程式必須宣告游標，並從游標逐一擷取每個資料列。使用游標的步驟如下：宣告游標、開啟游標、從游標擷取一個資料列、重複擷取，最後關閉游標。

使用游標查詢：

```

EXEC SQL DECLARE foo_bar CURSOR FOR
    SELECT number, ascii FROM foo
    ORDER BY ascii;
EXEC SQL OPEN foo_bar;
EXEC SQL FETCH foo_bar INTO :FooBar, DooDad;
...
EXEC SQL CLOSE foo_bar;
EXEC SQL COMMIT;
```

關於宣告游標的更多細節，請參閱 [DECLARE](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-declare.md)；關於從游標擷取資料列的更多細節，請參閱 [FETCH](https://docs.postgresql.tw/19/reference/sql-commands/sql-fetch.md)。

譯註：上方範例程式碼依原文保留；其中 FETCH 的 INTO 清單第二個目標 DooDad 少了主機變數必須有的冒號前綴，正確寫法應為 :DooDad。

#### 注意

ECPG 的 `DECLARE` 命令實際上並不會把陳述式送到 PostgreSQL 後端。游標是在執行 `OPEN` 命令的時候，才（使用後端的 `DECLARE` 命令）在後端開啟。

#### 34.3.3. 管理交易 [#](#ecpg-transactions) <a href="#ecpg-transactions" id="ecpg-transactions"></a>

本節內容請參閱[34.3.3. 管理交易](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-commands/ecpg-transactions.md#ecpg-transactions)。

#### 34.3.4. 預備陳述式 [#](#ecpg-prepared) <a href="#ecpg-prepared" id="ecpg-prepared"></a>

當要傳給 SQL 陳述式的值在編譯時期還不知道，或同一個陳述式將被使用很多次時，預備陳述式就很有用。

陳述式以 `PREPARE` 命令來準備。對於尚未知道的值，請使用預留位置「`?`」：

```

EXEC SQL PREPARE stmt1 FROM "SELECT oid, datname FROM pg_database WHERE oid = ?";
```

若陳述式傳回單一資料列，應用程式可以在 `PREPARE` 之後呼叫 `EXECUTE` 來執行該陳述式，並以 `USING` 子句提供預留位置的實際值：

```

EXEC SQL EXECUTE stmt1 INTO :dboid, :dbname USING 1;
```

若陳述式傳回多個資料列，應用程式可以使用以該預備陳述式為基礎宣告的游標。若要繫結輸入參數，必須以 `USING` 子句開啟游標：

```

EXEC SQL PREPARE stmt1 FROM "SELECT oid,datname FROM pg_database WHERE oid > ?";
EXEC SQL DECLARE foo_bar CURSOR FOR stmt1;

/* when end of result set reached, break out of while loop */
EXEC SQL WHENEVER NOT FOUND DO BREAK;

EXEC SQL OPEN foo_bar USING 100;
...
while (1)
{
    EXEC SQL FETCH NEXT FROM foo_bar INTO :dboid, :dbname;
    ...
}
EXEC SQL CLOSE foo_bar;
```

不再需要該預備陳述式時，你應該將它釋放：

```

EXEC SQL DEALLOCATE PREPARE name;
```

關於 `PREPARE` 的更多細節，請參閱 [PREPARE](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-sql-commands/ecpg-sql-prepare.md)。關於使用預留位置與輸入參數的更多細節，另請參閱[第 34.5 節](https://docs.postgresql.tw/19/client-interfaces/ecpg/ecpg-dynamic.md)。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/ecpg-commands.html)（原文版本：18.6；核對日期：2026-10-22）


---

# 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.postgresql.tw/19/client-interfaces/ecpg/ecpg-commands.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.
