A Connection represents a connection to a SQL database system.
Use a Connection to execute SQL statements. There are three ways to execute statements: Connection_execute() is used to execute SQL statements that do not return a result set. Such statements are INSERT, UPDATE or DELETE. Connection_executeQuery() is used to execute a SQL SELECT statement and return a result set. These methods can only handle values which can be expressed as C-strings. If you need to handle binary data, such as inserting a blob value into the database, use a PreparedStatement object to execute the SQL statement. The factory method Connection_prepareStatement() is used to obtain a PreparedStatement object.
The method Connection_executeQuery() will return an empty ResultSet (not null) if the SQL statement did not return any values. A ResultSet is valid until the next call to Connection execute or until the Connection is returned to the Connection Pool. If an error occurs during execution, an SQLException is thrown.
Any SQL statement that changes the database (basically, any SQL command other than SELECT) will automatically start a transaction if one is not already in effect. Automatically started transactions are committed at the conclusion of the command.
Transactions can also be started manually using Connection_beginTransaction(). Such transactions usually persist until the next call to Connection_commit() or Connection_rollback(). A transaction will also rollback if the database is closed or if an error occurs. Nested transactions are not allowed.
Examples
Basic Query Execution
if (con) {
printf(
"Name: %s, Age: %d\n",
valueOr(name,
"N/A"), age);
}
}
Connection_T ConnectionPool_getConnection(T P)
Get a connection from the pool.
ResultSet_T Connection_executeQuery(T C, const char *sql,...)
Executes a SQL query and returns a ResultSet.
void Connection_close(T C)
Returns the connection to the connection pool.
bool ResultSet_next(T R)
Moves the cursor to the next row.
int ResultSet_getInt(T R, int columnIndex)
Gets the designated column's value as an int.
const char * ResultSet_getString(T R, int columnIndex)
Gets the designated column's value as a C-string.
#define valueOr(expr, default_value)
Definition zdb.h:107
Transaction Example
Connection_T con = NULL;
{
Connection_execute(con,
"UPDATE accounts SET balance = balance - %f WHERE id = %d", 100.0, 1);
Connection_execute(con,
"UPDATE accounts SET balance = balance + %f WHERE id = %d", 100.0, 2);
printf("Transfer successful\n");
}
{
printf("Transfer failed: %s\n", Exception_frame.message);
}
{
}
Connection_T ConnectionPool_getConnectionOrException(T P)
Get a connection from the pool.
void Connection_beginTransaction(T C)
Begins a new (default) transaction.
void Connection_commit(T C)
Commits the current transaction.
void Connection_execute(T C, const char *sql,...)
Executes a SQL statement, with or without parameters.
#define ELSE
Defines a block containing code for handling any exception thrown in the TRY block.
Definition Exception.h:284
#define FINALLY
Defines a block of code that is subsequently executed whether an exception is thrown or not.
Definition Exception.h:295
#define TRY
Defines a block of code that can potentially throw an exception.
Definition Exception.h:256
#define END_TRY
Ends a TRY-CATCH block.
Definition Exception.h:306
Using PreparedStatement
if (con) {
const char *sql = "INSERT INTO logs (message, timestamp) VALUES (?, ?)";
}
PreparedStatement_T Connection_prepareStatement(T C, const char *sql,...)
Prepares a SQL statement for execution.
void PreparedStatement_setTimestamp(T P, int parameterIndex, time_t x)
Sets the in parameter at index parameterIndex to the given Unix timestamp value.
void PreparedStatement_setString(T P, int parameterIndex, const char *x)
Sets the in parameter at index parameterIndex to the given string value.
void PreparedStatement_execute(T P)
Executes the prepared SQL statement.
long long PreparedStatement_rowsChanged(T P)
Gets the number of rows affected by the most recent SQL statement.
A Connection is reentrant, but not thread-safe and should only be used by one thread (at a time).
- Note
- When Connection_close() is called on a Connection object, it is automatically returned to the pool. If the connection is still in a transaction at this point, the transaction will be automatically rolled back. This ensures data integrity even when exceptions occur. It's recommended to always call Connection_close() in a FINALLY block to guarantee proper resource management and transaction handling. See the Transaction Example above for a practical demonstration of this behavior.
- See also
- ResultSet.h PreparedStatement.h SQLException.h
|
|
void | Connection_setQueryTimeout (T C, int ms) |
| Sets the query timeout for this Connection.
|
|
int | Connection_getQueryTimeout (T C) |
| Gets the query timeout for this Connection.
|
|
void | Connection_setMaxRows (T C, int max) |
| Sets the maximum number of rows for ResultSet objects.
|
|
int | Connection_getMaxRows (T C) |
| Gets the maximum number of rows for ResultSet objects.
|
|
void | Connection_setFetchSize (T C, int rows) |
| Sets the number of rows to fetch for ResultSet objects.
|
|
int | Connection_getFetchSize (T C) |
| Gets the number of rows to fetch for ResultSet objects.
|
|
URL_T | Connection_getURL (T C) |
| Gets this Connections URL.
|
|
|
bool | Connection_ping (T C) |
| Pings the database server to check if the connection is alive.
|
|
void | Connection_clear (T C) |
| Clears any ResultSet and PreparedStatements in the Connection.
|
|
void | Connection_close (T C) |
| Returns the connection to the connection pool.
|
|
void | Connection_beginTransaction (T C) |
| Begins a new (default) transaction.
|
|
void | Connection_beginTransactionType (T C, TRANSACTION_TYPE type) |
| Begins a new specific transaction.
|
|
bool | Connection_inTransaction (T C) |
| Checks if this Connection is in an uncommitted transaction.
|
|
void | Connection_commit (T C) |
| Commits the current transaction.
|
|
void | Connection_rollback (T C) |
| Rolls back the current transaction.
|
|
long long | Connection_lastRowId (T C) |
| Gets the last inserted row ID for auto-increment columns.
|
|
long long | Connection_rowsChanged (T C) |
| Gets the number of rows affected by the last execute() statement.
|
|
void | Connection_execute (T C, const char *sql,...) |
| Executes a SQL statement, with or without parameters.
|
|
ResultSet_T | Connection_executeQuery (T C, const char *sql,...) |
| Executes a SQL query and returns a ResultSet.
|
|
PreparedStatement_T | Connection_prepareStatement (T C, const char *sql,...) |
| Prepares a SQL statement for execution.
|
|
const char * | Connection_getLastError (T C) |
| Gets the last SQL error message.
|
|
|
bool | Connection_isSupported (const char *url) |
| Checks if the specified database system is supported.
|
|
void Connection_execute |
( |
T | C, |
|
|
const char * | sql, |
|
|
| ... ) |
Executes a SQL statement, with or without parameters.
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. Several SQL statements can be used in the sql parameter string, each separated with the ;
SQL statement separator character. Note, calling this method clears any previous ResultSets associated with the Connection.
- Parameters
-
C | A Connection object |
sql | A SQL statement |
- Exceptions
-
SQLException | If a database error occurs. |
- See also
- SQLException.h