QSqlQuery Class
The QSqlQuery class provides a means of executing and manipulating SQL statements. More…
| Header | #include <QSqlQuery> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Sql) |
| Module | Nt SQL C++ Classes |
List of all members, including inherited members
Public Types
Public Functions
| QSqlQuery(QSqlResult *result) | |
| QSqlQuery(const QString &query = QString(), const QSqlDatabase &db = QSqlDatabase()) | |
| QSqlQuery(const QSqlDatabase &db) | |
| QSqlQuery(QSqlQuery &&other) | |
| QSqlQuery & | operator=(QSqlQuery &&other) |
| ~QSqlQuery() | |
| bool | isValid() const |
| bool | isActive() const |
| bool | isNull(int field) const |
| bool | isNull(QAnyStringView name) const |
| int | at() const |
| QString | lastQuery() const |
| int | numRowsAffected() const |
| QSqlError | lastError() const |
| bool | isSelect() const |
| int | size() const |
| const QSqlDriver * | driver() const |
| const QSqlResult * | result() const |
| bool | isForwardOnly() const |
| QSqlRecord | record() const |
| void | setForwardOnly(bool forward) |
| bool | exec(const QString &query) |
| QVariant | value(int i) const |
| QVariant | value(QAnyStringView name) const |
| void | setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy) |
| QSql::NumericalPrecisionPolicy | numericalPrecisionPolicy() const |
| bool | seek(int i, bool relative = false) |
| bool | next() |
| bool | previous() |
| bool | first() |
| bool | last() |
| void | clear() |
| bool | exec() |
| bool | execBatch(BatchExecutionMode mode = ValuesAsRows) |
| bool | prepare(const QString &query) |
| void | bindValue(const QString &placeholder, const QVariant &val, QSql::ParamType type = QSql::In) |
| void | bindValue(int pos, const QVariant &val, QSql::ParamType type = QSql::In) |
| void | addBindValue(const QVariant &val, QSql::ParamType type = QSql::In) |
| QVariant | boundValue(const QString &placeholder) const |
| QVariant | boundValue(int pos) const |
| QVariantList | boundValues() const |
| QStringList | boundValueNames() const |
| QString | boundValueName(int pos) const |
| QString | executedQuery() const |
| QVariant | lastInsertId() const |
| void | finish() |
| bool | nextResult() |
| void | swap(QSqlQuery &other) |
Detailed Description
A QSqlQuery runs SQL statements on a connection and walks the rows that a SELECT returns. Without a QSqlDatabase it uses the default connection.
QSqlQuery query("SELECT name, age FROM people ORDER BY name");
while (query.next()) {
QString name = query.value(0).toString();
int age = query.value(1).toInt();
}
After a successful exec() the query is active (isActive()) and positioned before the first row: next() moves to the first row and then on, and returns false after the last one. previous(), first(), last() and seek() move around freely, unless the query is forward-only. value() reads a field of the current row by position, or by name, which is slower; record() tells the names and positions.
Binding Values
Values belong in placeholders, not in the text of the statement: this keeps them apart from the SQL, whatever characters they contain, and the statement is prepared only once. Placeholders have names or are written ?:
QSqlQuery query;
query.prepare("INSERT INTO people (name, age) VALUES (:name, :age)");
query.bindValue(":name", "Ada");
query.bindValue(":age", 36);
query.exec();
query.prepare("SELECT name FROM people WHERE age > ?");
query.addBindValue(30);
query.exec();
The values stay bound: binding one of them again and calling exec() runs the statement with the others unchanged.
See also QSqlDatabase, QSqlRecord, QSqlQueryModel and Using Nt SQL.
Differences from Qt
A query can be moved but not copied; copying is deprecated in Qt 6. A statement with placeholders is always given to the driver with ? placeholders, so executedQuery() shows those; bound values are not written into its text. setPositionalBindingEnabled() is missing. execBatch() runs the statement once for each row with every driver. With the QSQLITE driver, size() is -1 for a SELECT, as in Qt, and a statement text that holds several statements is an error.
Member Type Documentation
enum QSqlQuery::BatchExecutionMode
How execBatch() reads the bound lists.
| Constant | Description |
|---|---|
QSqlQuery::ValuesAsRows | Each list holds the values of one placeholder, one item for each run of the statement. |
QSqlQuery::ValuesAsColumns | Each list is bound as a single value, for databases that take arrays. No driver of Nt does. |
Member Function Documentation
QSqlQuery::QSqlQuery(QSqlResult *result)
Constructs a query that uses result, which a driver made, and takes ownership of it.
QSqlQuery::QSqlQuery(const QString &query = QString(), const QSqlDatabase &db = QSqlDatabase())
Constructs a query on the connection db, or on the default connection if db is not valid. If query is not empty, it is run at once, as by exec().
See also QSqlDatabase::database().
QSqlQuery::QSqlQuery(const QSqlDatabase &db)
This is an overloaded function.
Constructs a query on the connection db.
QSqlQuery::QSqlQuery(QSqlQuery &&other)
Constructs a query that takes over the statement and the rows of other. other can only be assigned to or destroyed afterwards.
QSqlQuery::~QSqlQuery()
Destroys the query and releases what it holds of the database.
void QSqlQuery::addBindValue(const QVariant &val, QSql::ParamType type = QSql::In)
Binds the value val of the kind type to the next placeholder: the first call after prepare() or exec() binds the first one.
See also bindValue(), prepare() and exec().
int QSqlQuery::at() const
Returns the position of the current row, counted from 0, or QSql::BeforeFirstRow or QSql::AfterLastRow.
See also isValid() and seek().
void QSqlQuery::bindValue(const QString &placeholder, const QVariant &val, QSql::ParamType type = QSql::In)
Binds the value val to the placeholder called placeholder in the prepared statement; the name is written with its colon, as in ":id". A placeholder that appears several times gets the value each time. A null QVariant binds a null value. type tells the kind of the value; add QSql::Binary for binary data that is not a QByteArray.
Nothing happens if the statement has no such placeholder.
See also addBindValue(), prepare(), exec() and boundValue().
void QSqlQuery::bindValue(int pos, const QVariant &val, QSql::ParamType type = QSql::In)
This is an overloaded function.
Binds the value val of the kind type to the placeholder at position pos, counted from 0 in the order of the statement.
QVariant QSqlQuery::boundValue(const QString &placeholder) const
Returns the value that is bound to the placeholder called placeholder, or an invalid QVariant if there is none.
See also boundValues() and bindValue().
QVariant QSqlQuery::boundValue(int pos) const
This is an overloaded function.
Returns the value that is bound to the placeholder at position pos.
QString QSqlQuery::boundValueName(int pos) const
Returns the name of the placeholder at position pos, or an empty string if it has none.
This function was introduced in 6.6.
See also boundValueNames().
QStringList QSqlQuery::boundValueNames() const
Returns the names of the placeholders, in the order of the statement. A placeholder that is written ? has an empty name.
This function was introduced in 6.6.
See also boundValues() and boundValueName().
QVariantList QSqlQuery::boundValues() const
Returns the bound values, in the order of the placeholders in the statement.
See also boundValueNames() and boundValue().
void QSqlQuery::clear()
Releases the rows and the statement and makes the query inactive, with no error and no bound values. It keeps its connection, and whether it is forward-only.
See also finish().
const QSqlDriver * QSqlQuery::driver() const
Returns the driver of the connection of the query, or nullptr if the connection has been removed and its driver destroyed.
bool QSqlQuery::exec(const QString &query)
Runs the SQL statement query and returns true on success. The query is then active, and for a SELECT it is positioned before the first row. On failure, lastError() tells why.
query has to be one statement in the SQL of the database. It is run as it is: do not build it from values that come from outside, bind them with prepare() and bindValue() instead.
See also prepare(), next() and lastError().
bool QSqlQuery::exec()
This is an overloaded function.
Runs the statement that was prepared with prepare(), with the values that are bound to its placeholders, and returns true on success.
See also prepare(), bindValue() and addBindValue().
bool QSqlQuery::execBatch(BatchExecutionMode mode = ValuesAsRows)
Runs the prepared statement once for each row of a batch and returns true if every run succeeded. Each bound value has to be a QVariantList with the values of its placeholder, one for each run; a null QVariant in a list binds a null value.
QSqlQuery query;
query.prepare("INSERT INTO people (name, age) VALUES (?, ?)");
query.addBindValue(QVariantList{"Ada", "Grace"});
query.addBindValue(QVariantList{36, 45});
query.execBatch();
Wrap the batch in a transaction, to make it one change and much faster. mode other than ValuesAsRows is not supported and fails.
See also prepare(), addBindValue() and QSqlDatabase::transaction().
QString QSqlQuery::executedQuery() const
Returns the statement as it was given to the database: for a prepared statement, with a ? for each placeholder; otherwise the same as lastQuery().
See also lastQuery().
void QSqlQuery::finish()
Releases the rows of the statement and makes the query inactive, so that the database is free of it: with SQLite, an unfinished SELECT keeps a table locked and stops a transaction from being committed. The prepared statement and its bound values are kept, so exec() runs it again.
There is no need to call this for a query whose rows were all read or that is about to be destroyed.
See also clear(), prepare() and exec().
bool QSqlQuery::first()
Moves to the first row and returns true if there is one. Fails for a forward-only query that has left the first row.
bool QSqlQuery::isActive() const
Returns true if a statement was run with success and is not finished; otherwise returns false.
bool QSqlQuery::isForwardOnly() const
Returns true if the rows can only be read forwards, with next() and seek() to a later row; otherwise returns false.
See also setForwardOnly().
bool QSqlQuery::isNull(int field) const
Returns true if the field at position field of the current row is null, if the query is not on a row, or if there is no such field; otherwise returns false.
See also value().
bool QSqlQuery::isNull(QAnyStringView name) const
This is an overloaded function.
Returns true if the field called name of the current row is null.
bool QSqlQuery::isSelect() const
Returns true if the statement returns rows, as a SELECT does; otherwise returns false.
bool QSqlQuery::isValid() const
Returns true if the query is positioned on a row; otherwise returns false.
bool QSqlQuery::last()
Moves to the last row and returns true if there is one. at() then tells the number of rows, less one.
See also first() and previous().
QSqlError QSqlQuery::lastError() const
Returns what went wrong with the last statement, if anything did.
See also QSqlError.
QVariant QSqlQuery::lastInsertId() const
Returns the identifier that the database gave the row that this query inserted last, or an invalid QVariant if there is none or the driver does not tell; see QSqlDriver::LastInsertId.
QString QSqlQuery::lastQuery() const
Returns the text of the statement that was run or prepared last, as it was written.
See also executedQuery().
bool QSqlQuery::next()
Moves to the next row and returns true if there is one: to the first row if the query is before it. Returns false, leaving the query after the last row, when the rows are used up.
See also previous(), seek() and isValid().
bool QSqlQuery::nextResult()
Moves to the next result set of a statement that returns several, and returns true if there is one; see QSqlDriver::MultipleResultSets. The QSQLITE driver has none.
QSql::NumericalPrecisionPolicy QSqlQuery::numericalPrecisionPolicy() const
Returns how numbers of high precision are returned.
See also setNumericalPrecisionPolicy().
int QSqlQuery::numRowsAffected() const
Returns the number of rows that the last statement changed, or -1 if that is not known or the query is not active. For a SELECT, use size().
See also size().
QSqlQuery & QSqlQuery::operator=(QSqlQuery &&other)
Takes over the statement and the rows of other and returns a reference to this query.
bool QSqlQuery::prepare(const QString &query)
Prepares the statement query to be run with exec(), and returns true on success. The statement may have placeholders, with names such as :id or written ?, for values that are bound with bindValue() or addBindValue().
With most databases this fails if the statement has an error or names a table that does not exist; lastError() tells.
See also exec(), bindValue() and addBindValue().
bool QSqlQuery::previous()
Moves to the row before the current one and returns true if there is one: to the last row if the query is after it. Returns false, leaving the query before the first row, at the start. Fails for a forward-only query.
QSqlRecord QSqlQuery::record() const
Returns the fields of the query. On a row, the fields have the values of the row; otherwise their values are null. An inactive query gives an empty record.
See also value().
const QSqlResult * QSqlQuery::result() const
Returns the result that the driver made for this query.
bool QSqlQuery::seek(int i, bool relative = false)
Moves to the row at position i, counted from 0, and returns true if there is such a row. If relative is true, i is counted from the current row: a negative number goes back. If there is no such row, the query is left before the first or after the last row.
A forward-only query can only seek forwards.
See also next(), previous(), first(), last() and at().
void QSqlQuery::setForwardOnly(bool forward)
Sets whether the rows are only read forwards to forward. A forward-only query needs less memory, as the driver does not have to keep the rows that were read; previous(), first() once the first row has been passed, and seek() to an earlier row then fail. Call this before the statement is run.
See also isForwardOnly() and next().
void QSqlQuery::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
Sets how numbers of high precision are returned to precisionPolicy, from the next statement on.
See also numericalPrecisionPolicy().
int QSqlQuery::size() const
Returns the number of rows of a SELECT, or -1 if the query is not an active SELECT or if the driver does not know the number; see QSqlDriver::QuerySize. Count the rows with next(), or with last() and at().
See also numRowsAffected().
void QSqlQuery::swap(QSqlQuery &other)
Swaps this query with other.
QVariant QSqlQuery::value(int i) const
Returns the value of the field at position i of the current row. Fields are counted from 0, in the order of the SELECT; with SELECT * that order is up to the database, so name the columns.
Returns an invalid QVariant, with a warning, if the query is not on a row or there is no such field.
See also record(), isNull() and next().
QVariant QSqlQuery::value(QAnyStringView name) const
This is an overloaded function.
Returns the value of the field called name of the current row. This looks the name up each time; in a loop over many rows, get the position from record() once.