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

# dbBeginTransaction

> 执行 BEGIN TRANSACTION SQL 命令，以标记显式 SQL 事务的开始。

export const siteNameShort = "知行之桥";

执行 `BEGIN TRANSACTION` SQL 命令，指示显式 SQL 事务的起点。将此操作与 [dbEndTransaction](./op-db-end-transaction) 配合使用，在 dbBeginTransaction 和 dbEndTransaction 调用之间执行其他数据库操作。有关详细信息，请参阅[示例](#示例)。

## 必需的参数

* **driver**：跨平台版本中的 JDBC 驱动程序类名称，或 .NET 版本中的 ADO.NET 提供程序名称。
* **conn**：连接字符串或数据库 URL。

## 可选的参数

* **transactiontimeout**：此事务的超时时间（以秒为单位）。零 (`0`) 表示没有超时。默认值为 `60`。
* **transactionid**：事务的 ID。如果未设置，{siteNameShort} 会生成一个 GUID 用作事务 ID。

## 输出参数

* **transactionid**：事务的 ID。

## 示例

在此示例中，在 dbBeginTransaction 和 dbEndTransaction 之间执行数据库查询，从而创建 SQL 事务。为了确定事务的状态，需要检查每个查询的状态。如果所有查询都成功，则提交事务；否则回滚事务。

```xml theme={null}
<!-- Creating the input item and defining the SQL queries -->
<arc:set attr="db.driver" value="cdata.jdbc.mysql.MySQLDriver" />
<arc:set attr="db.conn" value="jdbc:cdata:mysql:server=localhost;port=3306;database=sakila;user=root;password=Password123;"/>
<arc:set attr="db.transactionaction" value="COMMIT" />
<arc:set attr="sql.queries#" value="ALTER TABLE Colors ADD Example varchar(255);"/>
<arc:set attr="sql.queries#" value="INSERT INTO Colors VALUES (27, Blue, Sky);" />
<arc:set attr="sql.queries#" value="INSERT INTO Colors VALUES (28, Red, Apple);" />
<arc:set attr="sql.queries#" value="INSERT INTO Colors VALUES (29, Yellow, Banana);" />

<arc:call op="dbBeginTransaction" in="db" out="dbbeginout">
  <arc:try>
    <!-- Enumerate and execute all queries and set the transactionaction based on the result -->
    <arc:enum attr="sql.queries">
      <arc:set attr="db.query" value="[_value]"/>
      <arc:call op="dbNonQuery" in="db" out="results" >
        <arc:set attr="db.transactionaction" value="[results.db:result | equals('success', 'COMMIT', 'ROLLBACK')]" />
      </arc:call>
      <!-- If any queries were flagged as rollback, stop running the queries -->
      <arc:if exp="[db.transactionaction | equals('ROLLBACK')]">
        <arc:break />
      </arc:if>
    </arc:enum>
    <!-- If any exception is raised, catch it and set the transactionaction to rollback -->
    <arc:catch>
      <arc:set attr="db.transactionaction" value="ROLLBACK" />
    </arc:catch>
    <!-- Finally, call dbEndTransaction to either commit or roll back the SQL transaction -->
    <arc:finally>
      <arc:set attr="db.transactionid" value="[dbbeginout.transactionid]" />
      <arc:call op="dbEndTransaction" in="db" />
    </arc:finally>
  </arc:try>
</arc:call>
```

只要在安装并运行 {siteNameShort} 的计算机上安装了驱动程序，就可以修改上面的示例以定位其他数据库。针对 .NET 调整此示例时，需要按如下方式更改 `driver` 和 `conn` 输入：

```xml theme={null}
<arc:set attr="db.driver" value="System.Data.CData.MySql" /> 
<arc:set attr="db.conn" value="Server=localhost;Database=sakila;UID=root;Password=Password123;"/>
```
