Represents a connection to a SQL database system.
Use a Connection to execute SQL statements. There are three ways to execute statements: execute() is used to execute SQL statements that do not return a result set. Such statements are INSERT, UPDATE or DELETE. 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 prepareStatement() is used to obtain a PreparedStatement object.
The method executeQuery() will return an empty ResultSet (not null) if the SQL statement did not return any values. A ResultSet lives until the next call to Connection execute or until the Connection is returned to the ConnectionPool. If an error occurs during execution, an sql_exception 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 beginTransaction(). Such transactions usually persist until the next call to commit() or 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
std::cout <<
"Name: " << result.
getString(
"name").value_or(
"N/A")
<<
", Age: " << result.
getInt(
"age") << std::endl;
}
Represents a connection to a SQL database system.
Definition zdbpp.h:1331
ResultSet executeQuery(const std::string &sql, Args &&... args)
Executes a SQL query and returns a ResultSet.
Definition zdbpp.h:1545
Represents a database result set.
Definition zdbpp.h:591
int getInt(int columnIndex)
Gets the designated column's value as an int.
Definition zdbpp.h:732
bool next()
Moves the cursor to the next row.
Definition zdbpp.h:678
std::optional< std::string_view > getString(int columnIndex)
Gets the designated column's value as a string.
Definition zdbpp.h:708
Transaction Example
try {
con.
execute(
"UPDATE accounts SET balance = balance - ? WHERE id = ?", 100.0, 1);
con.
execute(
"UPDATE accounts SET balance = balance + ? WHERE id = ?", 100.0, 2);
std::cout << "Transfer successful" << std::endl;
std::cerr << "Transfer failed: " << e.what() << std::endl;
}
void beginTransaction()
Begins a new transaction.
Definition zdbpp.h:1438
void execute(const std::string &sql, Args &&... args)
Executes a SQL statement, with or without parameters.
Definition zdbpp.h:1507
void commit()
Commits the current transaction.
Definition zdbpp.h:1452
Exception class for SQL related errors.
Definition zdbpp.h:276
Using PreparedStatement
auto stmt = con.
prepareStatement(
"INSERT INTO logs (message, timestamp) VALUES (?, ?)");
stmt.
bindValues(
"User logged in", std::time(
nullptr));
stmt.execute();
std::cout << "Rows affected: " << stmt.rowsChanged() << std::endl;
PreparedStatement prepareStatement(const std::string &sql)
Prepares a SQL statement for execution.
Definition zdbpp.h:1578
void bindValues(Args &&... args)
Binds multiple values to the Prepared Statement at once.
Definition zdbpp.h:1159
A Connection is reentrant, but not thread-safe and should only be used by one thread at a time.
- Note
- When a Connection object goes out of scope, 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, ensuring data integrity even in the face of exceptions.
- Warning
- Connection objects are internally managed by the ConnectionPool that created them and are not copyable or movable. Always ensure that the originating ConnectionPool object remains valid for the entire duration of the Connection's use. It is recommended to obtain a Connection, use it for a specific task, and then close it (return it to the pool) as soon as possible, rather than holding onto it for extended periods.
|
|
void | setQueryTimeout (int ms) noexcept |
| Sets the query timeout for this Connection.
|
|
int | getQueryTimeout () noexcept |
| Gets the query timeout for this Connection.
|
|
void | setMaxRows (int max) noexcept |
| Sets the maximum number of rows for ResultSet objects.
|
|
int | getMaxRows () noexcept |
| Gets the maximum number of rows for ResultSet objects.
|
|
void | setFetchSize (int rows) noexcept |
| Sets the number of rows to fetch for ResultSet objects.
|
|
int | getFetchSize () noexcept |
| Gets the number of rows to fetch for ResultSet objects.
|
|
|
bool | ping () noexcept |
| Pings the database server to check if the connection is alive.
|
|
void | clear () noexcept |
| Clears any ResultSet and PreparedStatements in the Connection.
|
|
void | close () noexcept |
| Returns the connection to the connection pool.
|
|
void | beginTransaction () |
| Begins a new transaction.
|
|
bool | inTransaction () const noexcept |
| Checks if this Connection is in an uncommitted transaction.
|
|
void | commit () |
| Commits the current transaction.
|
|
void | rollback () |
| Rolls back the current transaction.
|
|
long long | lastRowId () noexcept |
| Gets the last inserted row ID for auto-increment columns.
|
|
long long | rowsChanged () noexcept |
| Gets the number of rows affected by the last execute() statement.
|
|
template<typename... Args> |
void | execute (const std::string &sql, Args &&... args) |
| Executes a SQL statement, with or without parameters.
|
|
template<typename... Args> |
ResultSet | executeQuery (const std::string &sql, Args &&... args) |
| Executes a SQL query and returns a ResultSet.
|
|
PreparedStatement | prepareStatement (const std::string &sql) |
| Prepares a SQL statement for execution.
|
|
std::optional< std::string_view > | getLastError () const noexcept |
| Gets the last SQL error message.
|
|