Top  | Previous | Next

system.db.beginTransaction

Description

Begins a new database transaction. Database transactions are used to execute multiple queries in an atomic fashion. After executing queries, you must either commit the transaction to have your changes take effect, or rollback the transaction which will make all operations since the last commit not take place. The transaction is given a new unique string code, which is then returned. You can then use this code  as the tx argument for other system.db.* function calls to execute various types of queries using this transaction.

 

An open transaction consumes one database connection until it is closed. Because leaving connections open indefinitely would exhaust the connection pool, each transaction is given a timeout. Each time the transaction is used, the timeout timer is reset. For example, if you make a transaction with a timeout of one minute, you must use that transaction at least once a minute. If a transaction is detected to have timed out, it will be automatically closed and its transaction id will no longer be valid.

Syntax

system.db.beginTransaction(database, isolationLevel, timeout)

Parameters

String database - The name of the database connection to create a transaction in. Use "" for the project's default connection.

Integer isolationLevel - The transaction isolation level to use. Use one of the four constants: system.db.READ_COMMITTED, system.db.READ_UNCOMMITTED, system.db.REPEATABLE_READ, or system.db.SERIALIZABLE

Long timeout - The amount of time, in milliseconds, that this connection is allowed to remain open without being used. Timeout counter is reset any time a query or call is executed against the transaction, or when committed or rolled-back.

Returns

String - The new transaction ID. You'll use this ID as the "tx" argument for all other calls to have them execute against this transaction.

Scope

All

Examples

This example would start a transaction with a 5 second timeout against the project's default database, using the default isolation level. Then it executes a series of update calls, and commits and closes the transaction.

 

txId = system.db.beginTransaction(timeout=5000)

status=2

 

for machineId in range(8):

   system.db.runPrepUpdate("UPDATE MachineStatus SET status=? WHERE ID=?"

      args=[status, machineId], tx=txId)

 

system.db.commitTransaction(txId)

system.db.closeTransaction(txId)