Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QSqlQuery Class Reference

The QSqlQuery class provides a means of executing and manipulating SQL statements. More...

#include <qsqlquery.h>

+ Collaboration diagram for QSqlQuery:

Public Types

enum  BatchExecutionMode { ValuesAsRows , ValuesAsColumns }
 \value ValuesAsRows - Updates multiple rows. More...
 

Public Member Functions

 QSqlQuery (QSqlResult *r)
 Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database.
 
 QSqlQuery (const QString &query=QString(), const QSqlDatabase &db=QSqlDatabase())
 Constructs a QSqlQuery object using the SQL query and the database db.
 
 QSqlQuery (const QSqlDatabase &db)
 Constructs a QSqlQuery object using the database db.
 
 QSqlQuery (const QSqlQuery &other)=delete
 
QSqlQueryoperator= (const QSqlQuery &other)=delete
 
 QSqlQuery (QSqlQuery &&other) noexcept
 
 ~QSqlQuery ()
 Destroys the object and frees any allocated resources.
 
void swap (QSqlQuery &other) noexcept
 
bool isValid () const
 Returns true if the query is currently positioned on a valid record; otherwise returns false.
 
bool isActive () const
 Returns true if the query is {active}.
 
bool isNull (int field) const
 Returns true if the query is not \l{isActive()}{active}, the query is not positioned on a valid record, there is no such field, or the field is null; otherwise false.
 
bool isNull (const QString &name) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
bool isNull (QStringView name) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns true if there is no field with this name; otherwise returns isNull(int index) for the corresponding field index.
 
int at () const
 Returns the current internal position of the query.
 
QString lastQuery () const
 Returns the text of the current query being used, or an empty string if there is no current query text.
 
int numRowsAffected () const
 Returns the number of rows affected by the result's SQL statement, or -1 if it cannot be determined.
 
QSqlError lastError () const
 Returns error information about the last error (if any) that occurred with this query.
 
bool isSelect () const
 Returns true if the current query is a SELECT statement; otherwise returns false.
 
int size () const
 Returns the size of the result (number of rows returned), or -1 if the size cannot be determined or if the database does not support reporting information about query sizes.
 
const QSqlDriverdriver () const
 Returns the database driver associated with the query.
 
const QSqlResultresult () const
 Returns the result associated with the query.
 
bool isForwardOnly () const
 Returns \l forwardOnly.
 
QSqlRecord record () const
 Returns a QSqlRecord containing the field information for the current query.
 
void setForwardOnly (bool forward)
 Sets \l forwardOnly to forward.
 
bool exec (const QString &query)
 Executes the SQL in query.
 
QVariant value (int i) const
 Returns the value of field index in the current record.
 
QVariant value (const QString &name) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QVariant value (QStringView name) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the value of the field called name in the current record.
 
void setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy)
 Sets \l numericalPrecisionPolicy to precisionPolicy.
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy () const
 Returns the \l numericalPrecisionPolicy.
 
void setPositionalBindingEnabled (bool enable)
 Sets \l positionalBindingEnabled to enable.
 
bool isPositionalBindingEnabled () const
 Returns \l positionalBindingEnabled.
 
bool seek (int i, bool relative=false)
 Retrieves the record at position index, if available, and positions the query on the retrieved record.
 
bool next ()
 Retrieves the next record in the result, if available, and positions the query on the retrieved record.
 
bool previous ()
 Retrieves the previous record in the result, if available, and positions the query on the retrieved record.
 
bool first ()
 Retrieves the first record in the result, if available, and positions the query on the retrieved record.
 
bool last ()
 Retrieves the last record in the result, if available, and positions the query on the retrieved record.
 
void clear ()
 Clears the result set and releases any resources held by the query.
 
bool exec ()
 Executes a previously prepared SQL query.
 
bool execBatch (BatchExecutionMode mode=ValuesAsRows)
 Executes a previously prepared SQL query in a batch.
 
bool prepare (const QString &query)
 Prepares the SQL query query for execution.
 
void bindValue (const QString &placeholder, const QVariant &val, QSql::ParamType type=QSql::In)
 Set the placeholder placeholder to be bound to value val in the prepared statement.
 
void bindValue (int pos, const QVariant &val, QSql::ParamType type=QSql::In)
 Set the placeholder in position pos to be bound to value val in the prepared statement.
 
void addBindValue (const QVariant &val, QSql::ParamType type=QSql::In)
 Adds the value val to the list of values when using positional value binding.
 
QVariant boundValue (const QString &placeholder) const
 Returns the value for the placeholder.
 
QVariant boundValue (int pos) const
 Returns the value for the placeholder at position pos.
 
QVariantList boundValues () const
 
QStringList boundValueNames () const
 
QString boundValueName (int pos) const
 
QString executedQuery () const
 Returns the last query that was successfully executed.
 
QVariant lastInsertId () const
 Returns the object ID of the most recent inserted row if the database supports it.
 
void finish ()
 Instruct the database driver that no more data will be fetched from this query until it is re-executed.
 
bool nextResult ()
 Discards the current result set and navigates to the next if available.
 

Properties

bool forwardOnly
 
bool positionalBindingEnabled
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy
 

Detailed Description

The QSqlQuery class provides a means of executing and manipulating SQL statements.

\inmodule QtSql

QSqlQuery encapsulates the functionality involved in creating, navigating and retrieving data from SQL queries which are executed on a \l QSqlDatabase. It can be used to execute DML (data manipulation language) statements, such as SELECT, INSERT, UPDATE and DELETE, as well as DDL (data definition language) statements, such as {CREATE} {TABLE}. It can also be used to execute database-specific commands which are not standard SQL (e.g. {SET DATESTYLE=ISO} for PostgreSQL).

Successfully executed SQL statements set the query's state to active so that isActive() returns true. Otherwise the query's state is set to inactive. In either case, when executing a new SQL statement, the query is positioned on an invalid record. An active query must be navigated to a valid record (so that isValid() returns true) before values can be retrieved.

For some databases, if an active query that is a {SELECT} statement exists when you call \l{QSqlDatabase::}{commit()} or \l{QSqlDatabase::}{rollback()}, the commit or rollback will fail. See isActive() for details.

\target QSqlQuery examples

Navigating records is performed with the following functions:

\list

These functions allow the programmer to move forward, backward or arbitrarily through the records returned by the query. If you only need to move forward through the results (e.g., by using next()), you can use setForwardOnly(), which will save a significant amount of memory overhead and improve performance on some databases. Once an active query is positioned on a valid record, data can be retrieved using value(). All data is transferred from the SQL backend using QVariants.

For example:

QSqlQuery query("SELECT country FROM artist");
while (query.next()) {
QString country = query.value(0).toString();
doSomething(country);
}

To access the data returned by a query, use value(int). Each field in the data returned by a SELECT statement is accessed by passing the field's position in the statement, starting from 0. This makes using {SELECT *} queries inadvisable because the order of the fields returned is indeterminate.

For the sake of efficiency, there are no functions to access a field by name (unless you use prepared queries with names, as explained below). To convert a field name into an index, use record().\l{QSqlRecord::indexOf()}{indexOf()}, for example:

QSqlQuery query("SELECT * FROM artist");
int fieldNo = query.record().indexOf("country");
while (query.next()) {
QString country = query.value(fieldNo).toString();
doSomething(country);
}

QSqlQuery supports prepared query execution and the binding of parameter values to placeholders. Some databases don't support these features, so for those, Qt emulates the required functionality. For example, the Oracle and ODBC drivers have proper prepared query support, and Qt makes use of it; but for databases that don't have this support, Qt implements the feature itself, e.g. by replacing placeholders with actual values when a query is executed. Use numRowsAffected() to find out how many rows were affected by a non-SELECT query, and size() to find how many were retrieved by a SELECT.

Oracle databases identify placeholders by using a colon-name syntax, e.g {:name}. ODBC simply uses ? characters. Qt supports both syntaxes, with the restriction that you can't mix them in the same query.

You can retrieve the values of all the fields in a single variable using boundValues().

Note
Not all SQL operations support binding values. Refer to your database system's documentation to check their availability.

Definition at line 23 of file qsqlquery.h.

Member Enumeration Documentation

◆ BatchExecutionMode

\value ValuesAsRows - Updates multiple rows.

Treats every entry in a QVariantList as a value for updating the next row. \value ValuesAsColumns - Updates a single row. Treats every entry in a QVariantList as a single value of an array type.

Enumerator
ValuesAsRows 
ValuesAsColumns 

Definition at line 93 of file qsqlquery.h.

Constructor & Destructor Documentation

◆ QSqlQuery() [1/5]

QSqlQuery::QSqlQuery ( QSqlResult * r)
explicit

Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database.

Definition at line 204 of file qsqlquery.cpp.

References d.

◆ QSqlQuery() [2/5]

QSqlQuery::QSqlQuery ( const QString & query = QString(),
const QSqlDatabase & db = QSqlDatabase() )
explicit

Constructs a QSqlQuery object using the SQL query and the database db.

If db is not specified, or is invalid, the application's default database is used. If query is not an empty string, it will be executed.

See also
QSqlDatabase

Definition at line 295 of file qsqlquery.cpp.

References d, db, and qInit().

+ Here is the call graph for this function:

◆ QSqlQuery() [3/5]

QSqlQuery::QSqlQuery ( const QSqlDatabase & db)
explicit

Constructs a QSqlQuery object using the database db.

If db is invalid, the application's default database will be used.

See also
QSqlDatabase

Definition at line 308 of file qsqlquery.cpp.

References d, db, and qInit().

+ Here is the call graph for this function:

◆ QSqlQuery() [4/5]

QSqlQuery::QSqlQuery ( const QSqlQuery & other)
delete

◆ QSqlQuery() [5/5]

QSqlQuery::QSqlQuery ( QSqlQuery && other)
inlinenoexcept
Since
6.2 Move-constructs a QSqlQuery from other.

Definition at line 45 of file qsqlquery.h.

◆ ~QSqlQuery()

QSqlQuery::~QSqlQuery ( )

Destroys the object and frees any allocated resources.

Definition at line 213 of file qsqlquery.cpp.

References d.

Member Function Documentation

◆ addBindValue()

void QSqlQuery::addBindValue ( const QVariant & val,
QSql::ParamType paramType = QSql::In )

Adds the value val to the list of values when using positional value binding.

The order of the addBindValue() calls determines which placeholder a value will be bound to in the prepared query. If paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.

To bind a NULL value, use a null QVariant; for example, use {QVariant(QMetaType::fromType<QString>())} if you are binding a string.

See also
bindValue(), prepare(), exec(), boundValue(), boundValues()

Definition at line 1146 of file qsqlquery.cpp.

References d.

Referenced by QSqlTableModelPrivate::exec().

+ Here is the caller graph for this function:

◆ at()

int QSqlQuery::at ( ) const

Returns the current internal position of the query.

The first record is at position zero. If the position is invalid, the function returns QSql::BeforeFirstRow or QSql::AfterLastRow, which are special negative values.

See also
previous(), next(), first(), last(), seek(), isActive(), isValid()

Definition at line 484 of file qsqlquery.cpp.

References d.

◆ bindValue() [1/2]

void QSqlQuery::bindValue ( const QString & placeholder,
const QVariant & val,
QSql::ParamType paramType = QSql::In )

Set the placeholder placeholder to be bound to value val in the prepared statement.

Note that the placeholder mark (e.g {:}) must be included when specifying the placeholder name. If paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call. In this case, sufficient space must be pre-allocated to store the result into.

To bind a NULL value, use a null QVariant; for example, use {QVariant(QMetaType::fromType<QString>())} if you are binding a string.

See also
addBindValue(), prepare(), exec(), boundValue(), boundValues()

Definition at line 1116 of file qsqlquery.cpp.

References d.

◆ bindValue() [2/2]

void QSqlQuery::bindValue ( int pos,
const QVariant & val,
QSql::ParamType paramType = QSql::In )

Set the placeholder in position pos to be bound to value val in the prepared statement.

Field numbering starts at 0. If paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.

Definition at line 1129 of file qsqlquery.cpp.

References d, and pos.

◆ boundValue() [1/2]

QVariant QSqlQuery::boundValue ( const QString & placeholder) const

Returns the value for the placeholder.

See also
boundValues(), bindValue(), addBindValue()

Definition at line 1156 of file qsqlquery.cpp.

References d.

◆ boundValue() [2/2]

QVariant QSqlQuery::boundValue ( int pos) const

Returns the value for the placeholder at position pos.

See also
boundValues()

Definition at line 1165 of file qsqlquery.cpp.

References d, and pos.

◆ boundValueName()

QString QSqlQuery::boundValueName ( int pos) const
Since
6.6

Returns the bound value name at position pos.

The order of the list is in binding order, irrespective of whether named or positional binding is used.

See also
boundValueNames()

Definition at line 1216 of file qsqlquery.cpp.

References d, and pos.

◆ boundValueNames()

QStringList QSqlQuery::boundValueNames ( ) const
Since
6.6

Returns the names of all bound values.

The order of the list is in binding order, irrespective of whether named or positional binding is used.

See also
boundValues(), boundValueName()

Definition at line 1201 of file qsqlquery.cpp.

References d.

◆ boundValues()

QVariantList QSqlQuery::boundValues ( ) const
Since
6.0

Returns a list of bound values.

The order of the list is in binding order, irrespective of whether named or positional binding is used.

The bound values can be examined in the following way:

const QVariantList list = query.boundValues();
for (qsizetype i = 0; i < list.size(); ++i)
qDebug() << i << ":" << list.at(i).toString();
See also
boundValue(), bindValue(), addBindValue(), boundValueNames()

Definition at line 1185 of file qsqlquery.cpp.

References d.

◆ clear()

void QSqlQuery::clear ( )

Clears the result set and releases any resources held by the query.

Sets the query state to inactive. You should rarely if ever need to call this function.

Definition at line 958 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::clear().

+ Here is the caller graph for this function:

◆ driver()

const QSqlDriver * QSqlQuery::driver ( ) const

Returns the database driver associated with the query.

Definition at line 505 of file qsqlquery.cpp.

References d.

Referenced by QSqlTableModelPrivate::exec().

+ Here is the caller graph for this function:

◆ exec() [1/2]

bool QSqlQuery::exec ( )

Executes a previously prepared SQL query.

Returns true if the query executed successfully; otherwise returns false.

Note that the last error for this query is reset when exec() is called.

See also
prepare(), bindValue(), addBindValue(), boundValue(), boundValues()

Definition at line 1029 of file qsqlquery.cpp.

References d, qCDebug, and QElapsedTimer::start().

+ Here is the call graph for this function:

◆ exec() [2/2]

bool QSqlQuery::exec ( const QString & query)

Executes the SQL in query.

Returns true and sets the query state to \l{isActive()}{active} if the query was successful; otherwise returns false. The query string must use syntax appropriate for the SQL database being queried (for example, standard SQL).

After the query is executed, the query is positioned on an invalid record and must be navigated to a valid record before data values can be retrieved (for example, using next()).

Note that the last error for this query is reset when exec() is called.

For SQLite, the query string can contain only one statement at a time. If more than one statement is given, the function returns false.

Example:

query.exec("INSERT INTO employee (id, name, salary) "
"VALUES (1001, 'Thad Beaumont', 65000)");
See also
isActive(), isValid(), next(), previous(), first(), last(), seek()

Definition at line 381 of file qsqlquery.cpp.

References QSql::BeforeFirstRow, d, qCDebug, qCWarning, setForwardOnly(), and QElapsedTimer::start().

Referenced by QSqlTableModelPrivate::exec(), exProc(), sql_intro_snippets(), testProc(), and updTable2().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ execBatch()

bool QSqlQuery::execBatch ( BatchExecutionMode mode = ValuesAsRows)

Executes a previously prepared SQL query in a batch.

All the bound parameters have to be lists of variants. If the database doesn't support batch executions, the driver will simulate it using conventional exec() calls.

Returns true if the query is executed successfully; otherwise returns false.

Example:

q.prepare("insert into myTable values (?, ?)");
ints << 1 << 2 << 3 << 4;
q.addBindValue(ints);
names << "Harald" << "Boris" << "Trond" << QVariant(QMetaType::fromType<QString>());
q.addBindValue(names);
if (!q.execBatch())
qDebug() << q.lastError();

The example above inserts four new rows into myTable:

1 Harald
2 Boris
3 Trond
4 NULL
const char SELECT[]
SELECT surname FROM people

To bind NULL values, a null QVariant of the relevant type has to be added to the bound QVariantList; for example, {QVariant(QMetaType::fromType<QString>())} should be used if you are using strings.

Note
Every bound QVariantList must contain the same amount of variants.
The type of the QVariants in a list must not change. For example, you cannot mix integer and string variants within a QVariantList.

The mode parameter indicates how the bound QVariantList will be interpreted. If mode is ValuesAsRows, every variant within the QVariantList will be interpreted as a value for a new row. ValuesAsColumns is a special case for the Oracle driver. In this mode, every entry within a QVariantList will be interpreted as array-value for an IN or OUT value within a stored procedure. Note that this will only work if the IN or OUT value is a table-type consisting of only one column of a basic type, for example {TYPE myType IS TABLE OF VARCHAR(64) INDEX BY BINARY_INTEGER;}

See also
prepare(), bindValue(), addBindValue()

Definition at line 1096 of file qsqlquery.cpp.

References d.

◆ executedQuery()

QString QSqlQuery::executedQuery ( ) const

Returns the last query that was successfully executed.

In most cases this function returns the same string as lastQuery(). If a prepared query with placeholders is executed on a DBMS that does not support it, the preparation of this query is emulated. The placeholders in the original query are replaced with their bound values to form a new query. This function returns the modified query. It is mostly useful for debugging purposes.

See also
lastQuery()

Definition at line 1233 of file qsqlquery.cpp.

References d.

◆ finish()

void QSqlQuery::finish ( )

Instruct the database driver that no more data will be fetched from this query until it is re-executed.

There is normally no need to call this function, but it may be helpful in order to free resources such as locks or cursors if you intend to re-use the query at a later time.

Sets the query to inactive. Bound values retain their values.

See also
prepare(), exec(), isActive()

Definition at line 1344 of file qsqlquery.cpp.

References QSql::BeforeFirstRow, d, and isActive.

◆ first()

bool QSqlQuery::first ( )

Retrieves the first record in the result, if available, and positions the query on the retrieved record.

Note that the result must be in the \l{isActive()}{active} state and isSelect() must return true before calling this function or it will do nothing and return false. Returns true if successful. If unsuccessful the query position is set to an invalid position and false is returned.

See also
next(), previous(), last(), seek(), at(), isActive(), isValid()

Definition at line 751 of file qsqlquery.cpp.

References at, QSql::BeforeFirstRow, d, isActive, and qCWarning.

◆ isActive()

bool QSqlQuery::isActive ( ) const

Returns true if the query is {active}.

An active QSqlQuery is one that has been \l{QSqlQuery::exec()} {exec()'d} successfully but not yet finished with. When you are finished with an active query, you can make the query inactive by calling finish() or clear(), or you can delete the QSqlQuery instance.

Note
Of particular interest is an active query that is a {SELECT} statement. For some databases that support transactions, an active query that is a {SELECT} statement can cause a \l{QSqlDatabase::} {commit()} or a \l{QSqlDatabase::} {rollback()} to fail, so before committing or rolling back, you should make your active {SELECT} statement query inactive using one of the ways listed above.
See also
isSelect()

Definition at line 855 of file qsqlquery.cpp.

References d.

◆ isForwardOnly()

bool QSqlQuery::isForwardOnly ( ) const

Returns \l forwardOnly.

See also
forwardOnly, next(), seek()

Definition at line 875 of file qsqlquery.cpp.

References d.

◆ isNull() [1/3]

bool QSqlQuery::isNull ( const QString & name) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 334 of file qsqlquery.cpp.

◆ isNull() [2/3]

bool QSqlQuery::isNull ( int field) const

Returns true if the query is not \l{isActive()}{active}, the query is not positioned on a valid record, there is no such field, or the field is null; otherwise false.

Note that for some drivers, isNull() will not return accurate information until after an attempt is made to retrieve data.

See also
isActive(), isValid(), value()

Definition at line 324 of file qsqlquery.cpp.

References d.

◆ isNull() [3/3]

bool QSqlQuery::isNull ( QStringView name) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns true if there is no field with this name; otherwise returns isNull(int index) for the corresponding field index.

This overload is less efficient than \l{QSqlQuery::}{isNull()}

Definition at line 347 of file qsqlquery.cpp.

References d, qCWarning, and qUtf16Printable.

◆ isPositionalBindingEnabled()

bool QSqlQuery::isPositionalBindingEnabled ( ) const

Returns \l positionalBindingEnabled.

Since
6.7
See also
positionalBindingEnabled

Definition at line 1327 of file qsqlquery.cpp.

References d.

◆ isSelect()

bool QSqlQuery::isSelect ( ) const

Returns true if the current query is a SELECT statement; otherwise returns false.

Definition at line 865 of file qsqlquery.cpp.

References d.

◆ isValid()

bool QSqlQuery::isValid ( ) const

Returns true if the query is currently positioned on a valid record; otherwise returns false.

Definition at line 833 of file qsqlquery.cpp.

References d, and QSqlError::isValid().

+ Here is the call graph for this function:

◆ last()

bool QSqlQuery::last ( )

Retrieves the last record in the result, if available, and positions the query on the retrieved record.

Note that the result must be in the \l{isActive()}{active} state and isSelect() must return true before calling this function or it will do nothing and return false. Returns true if successful. If unsuccessful the query position is set to an invalid position and false is returned.

See also
next(), previous(), first(), seek(), at(), isActive(), isValid()

Definition at line 774 of file qsqlquery.cpp.

References d, and isActive.

◆ lastError()

QSqlError QSqlQuery::lastError ( ) const

Returns error information about the last error (if any) that occurred with this query.

See also
QSqlError, QSqlDatabase::lastError()

Definition at line 823 of file qsqlquery.cpp.

References d.

Referenced by QSqlTableModelPrivate::exec().

+ Here is the caller graph for this function:

◆ lastInsertId()

QVariant QSqlQuery::lastInsertId ( ) const

Returns the object ID of the most recent inserted row if the database supports it.

An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back. If more than one row was touched by the insert, the behavior is undefined.

For MySQL databases the row's auto-increment field will be returned.

Note
For this function to work in PSQL, the table must contain OIDs, which may not have been created by default. Check the default_with_oids configuration variable to be sure.
See also
QSqlDriver::hasFeature()

Definition at line 1253 of file qsqlquery.cpp.

References d.

◆ lastQuery()

QString QSqlQuery::lastQuery ( ) const

Returns the text of the current query being used, or an empty string if there is no current query text.

See also
executedQuery()

Definition at line 496 of file qsqlquery.cpp.

References d.

Referenced by QSqlTableModelPrivate::exec().

+ Here is the caller graph for this function:

◆ next()

bool QSqlQuery::next ( )

Retrieves the next record in the result, if available, and positions the query on the retrieved record.

Note that the result must be in the \l{isActive()}{active} state and isSelect() must return true before calling this function or it will do nothing and return false.

The following rules apply:

\list

  • If the result is currently located before the first record, e.g. immediately after a query is executed, an attempt is made to retrieve the first record.
  • If the result is currently located after the last record, there is no change and false is returned.
  • If the result is located somewhere in the middle, an attempt is made to retrieve the next record.

\endlist

If the record could not be retrieved, the result is positioned after the last record and false is returned. If the record is successfully retrieved, true is returned.

See also
previous(), first(), last(), seek(), at(), isActive(), isValid()

Definition at line 670 of file qsqlquery.cpp.

References QSql::AfterLastRow, at, QSql::BeforeFirstRow, d, and isActive.

◆ nextResult()

bool QSqlQuery::nextResult ( )

Discards the current result set and navigates to the next if available.

Some databases are capable of returning multiple result sets for stored procedures or SQL batches (a query strings that contains multiple statements). If multiple result sets are available after executing a query this function can be used to navigate to the next result set(s).

If a new result set is available this function will return true. The query will be repositioned on an invalid record in the new result set and must be navigated to a valid record before data values can be retrieved. If a new result set isn't available the function returns false and the query is set to inactive. In any case the old result set will be discarded.

When one of the statements is a non-select statement a count of affected rows may be available instead of a result set.

Note that some databases, i.e. Microsoft SQL Server, requires non-scrollable cursors when working with multiple result sets. Some databases may execute all statements at once while others may delay the execution until the result set is actually accessed, and some databases may have restrictions on which statements are allowed to be used in a SQL batch.

See also
QSqlDriver::hasFeature(), forwardOnly, next(), isSelect(), numRowsAffected(), isActive(), lastError()

Definition at line 1383 of file qsqlquery.cpp.

References d, and isActive.

◆ numericalPrecisionPolicy()

QSql::NumericalPrecisionPolicy QSqlQuery::numericalPrecisionPolicy ( ) const

Returns the \l numericalPrecisionPolicy.

Definition at line 1293 of file qsqlquery.cpp.

References d.

◆ numRowsAffected()

int QSqlQuery::numRowsAffected ( ) const

Returns the number of rows affected by the result's SQL statement, or -1 if it cannot be determined.

Note that for SELECT statements, the value is undefined; use size() instead. If the query is not \l{isActive()}{active}, -1 is returned.

See also
size(), QSqlDriver::hasFeature()

Definition at line 809 of file qsqlquery.cpp.

References d, and isActive.

◆ operator=()

QSqlQuery & QSqlQuery::operator= ( const QSqlQuery & other)
delete
Since
6.2 Move-assigns other to this object.

◆ prepare()

bool QSqlQuery::prepare ( const QString & query)

Prepares the SQL query query for execution.

Returns true if the query is prepared successfully; otherwise returns false.

The query may contain placeholders for binding values. Both Oracle style colon-name (e.g., {:surname}), and ODBC style ({?}) placeholders are supported; but they cannot be mixed in the same query. See the \l{QSqlQuery examples}{Detailed Description} for examples.

Portability notes: Some databases choose to delay preparing a query until it is executed the first time. In this case, preparing a syntactically wrong query succeeds, but every consecutive exec() will fail. When the database does not support named placeholders directly, the placeholder can only contain characters in the range [a-zA-Z0-9_].

For SQLite, the query string can contain only one statement at a time. If more than one statement is given, the function returns false.

Example:

query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();
See also
exec(), bindValue(), addBindValue()

Definition at line 989 of file qsqlquery.cpp.

References QSql::BeforeFirstRow, d, qCDebug, qCWarning, qUtf16Printable, and setForwardOnly().

Referenced by callOutProc(), QSqlTableModelPrivate::exec(), insertVariants(), QSqlQuery_snippets(), selectEmployees(), and sql_intro_snippets().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ previous()

bool QSqlQuery::previous ( )

Retrieves the previous record in the result, if available, and positions the query on the retrieved record.

Note that the result must be in the \l{isActive()}{active} state and isSelect() must return true before calling this function or it will do nothing and return false.

The following rules apply:

\list

  • If the result is currently located before the first record, there is no change and false is returned.
  • If the result is currently located after the last record, an attempt is made to retrieve the last record.
  • If the result is somewhere in the middle, an attempt is made to retrieve the previous record.

\endlist

If the record could not be retrieved, the result is positioned before the first record and false is returned. If the record is successfully retrieved, true is returned.

See also
next(), first(), last(), seek(), at(), isActive(), isValid()

Definition at line 718 of file qsqlquery.cpp.

References QSql::AfterLastRow, at, QSql::BeforeFirstRow, d, isActive, and qCWarning.

◆ record()

QSqlRecord QSqlQuery::record ( ) const

Returns a QSqlRecord containing the field information for the current query.

If the query points to a valid row (isValid() returns true), the record is populated with the row's values. An empty record is returned when there is no active query (isActive() returns false).

To retrieve values from a query, value() should be used since its index-based lookup is faster.

In the following example, a {SELECT * FROM} query is executed. Since the order of the columns is not defined, QSqlRecord::indexOf() is used to obtain the index of a column.

QSqlQuery q("select * from employees");
QSqlRecord rec = q.record();
qDebug() << "Number of columns: " << rec.count();
int nameCol = rec.indexOf("name"); // index of the field "name"
while (q.next())
qDebug() << q.value(nameCol).toString(); // output all names
See also
value()

Definition at line 942 of file qsqlquery.cpp.

References QSqlRecord::count(), d, i, and QSqlRecord::setValue().

+ Here is the call graph for this function:

◆ result()

const QSqlResult * QSqlQuery::result ( ) const

Returns the result associated with the query.

Definition at line 514 of file qsqlquery.cpp.

References d.

◆ seek()

bool QSqlQuery::seek ( int index,
bool relative = false )

Retrieves the record at position index, if available, and positions the query on the retrieved record.

The first record is at position 0. Note that the query must be in an \l{isActive()} {active} state and isSelect() must return true before calling this function.

If relative is false (the default), the following rules apply:

\list

  • If index is negative, the result is positioned before the first record and false is returned.
  • Otherwise, an attempt is made to move to the record at position index. If the record at position index could not be retrieved, the result is positioned after the last record and false is returned. If the record is successfully retrieved, true is returned.

\endlist

If relative is true, the following rules apply:

\list

  • If the result is currently positioned before the first record and: \list
  • index is negative or zero, there is no change, and false is returned.
  • index is positive, an attempt is made to position the result at absolute position index - 1, following the sames rule for non relative seek, above. \endlist
  • If the result is currently positioned after the last record and: \list
  • index is positive or zero, there is no change, and false is returned.
  • index is negative, an attempt is made to position the result at index + 1 relative position from last record, following the rule below. \endlist
  • If the result is currently located somewhere in the middle, and the relative offset index moves the result below zero, the result is positioned before the first record and false is returned.
  • Otherwise, an attempt is made to move to the record index records ahead of the current record (or index records behind the current record if index is negative). If the record at offset index could not be retrieved, the result is positioned after the last record if index >= 0, (or before the first record if index is negative), and false is returned. If the record is successfully retrieved, true is returned.

\endlist

See also
next(), previous(), first(), last(), at(), isActive(), isValid()

Definition at line 578 of file qsqlquery.cpp.

References QSql::AfterLastRow, at, QSql::BeforeFirstRow, d, isActive, qCWarning, and QSqlResult::setAt().

+ Here is the call graph for this function:

◆ setForwardOnly()

void QSqlQuery::setForwardOnly ( bool forward)

Sets \l forwardOnly to forward.

See also
forwardOnly, next(), seek()

Definition at line 919 of file qsqlquery.cpp.

References d.

Referenced by callStoredProc(), and updTable2().

+ Here is the caller graph for this function:

◆ setNumericalPrecisionPolicy()

void QSqlQuery::setNumericalPrecisionPolicy ( QSql::NumericalPrecisionPolicy precisionPolicy)

Sets \l numericalPrecisionPolicy to precisionPolicy.

Definition at line 1285 of file qsqlquery.cpp.

References d.

◆ setPositionalBindingEnabled()

void QSqlQuery::setPositionalBindingEnabled ( bool enable)

Sets \l positionalBindingEnabled to enable.

Since
6.7
See also
positionalBindingEnabled

Definition at line 1317 of file qsqlquery.cpp.

References d.

◆ size()

int QSqlQuery::size ( ) const

Returns the size of the result (number of rows returned), or -1 if the size cannot be determined or if the database does not support reporting information about query sizes.

Note that for non-SELECT statements (isSelect() returns false), size() will return -1. If the query is not active (isActive() returns false), -1 is returned.

To determine the number of rows affected by a non-SELECT statement, use numRowsAffected().

See also
isActive(), numRowsAffected(), QSqlDriver::hasFeature()

Definition at line 793 of file qsqlquery.cpp.

References d, isActive, and QSqlDriver::QuerySize.

◆ swap()

void QSqlQuery::swap ( QSqlQuery & other)
inlinenoexcept
Since
6.2 Swaps other to this object. This operation is very fast and never fails.

Definition at line 52 of file qsqlquery.h.

References d, other(), and qt_ptr_swap().

+ Here is the call graph for this function:

◆ value() [1/3]

QVariant QSqlQuery::value ( const QString & name) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 453 of file qsqlquery.cpp.

◆ value() [2/3]

QVariant QSqlQuery::value ( int index) const

Returns the value of field index in the current record.

The fields are numbered from left to right using the text of the SELECT statement, e.g. in

field 0 is forename and field 1 is surname. Using {SELECT *} is not recommended because the order of the fields in the query is undefined.

An invalid QVariant is returned if field index does not exist, if the query is inactive, or if the query is positioned on an invalid record.

See also
previous(), next(), first(), last(), seek(), isActive(), isValid()

Definition at line 442 of file qsqlquery.cpp.

References d, QVariant::data(), isActive, and qCWarning.

+ Here is the call graph for this function:

◆ value() [3/3]

QVariant QSqlQuery::value ( QStringView name) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Returns the value of the field called name in the current record.

If field name does not exist an invalid variant is returned.

This overload is less efficient than \l{QSqlQuery::}{value()}

Definition at line 466 of file qsqlquery.cpp.

References d, qCWarning, and qUtf16Printable.

Property Documentation

◆ forwardOnly

QSqlQuery::forwardOnly
readwrite
Since
6.8

This property holds the forward only mode. If forward is true, only next() and seek() with positive values, are allowed for navigating the results.

Forward only mode can be (depending on the driver) more memory efficient since results do not need to be cached. It will also improve performance on some databases. For this to be true, you must call setForwardOnly() before the query is prepared or executed. Note that the constructor that takes a query and a database may execute the query.

Forward only mode is off by default.

Setting forward only to false is a suggestion to the database engine, which has the final say on whether a result set is forward only or scrollable. isForwardOnly() will always return the correct status of the result set.

Note
Calling setForwardOnly after execution of the query will result in unexpected results at best, and crashes at worst.
To make sure the forward-only query completed successfully, the application should check lastError() for an error not only after executing the query, but also after navigating the query results.
Warning
PostgreSQL: While navigating the query results in forward-only mode, do not execute any other SQL command on the same database connection. This will cause the query results to be lost.
See also
next(), seek()

Definition at line 27 of file qsqlquery.h.

◆ numericalPrecisionPolicy

QSqlQuery::numericalPrecisionPolicy
readwrite
Since
6.8

Instruct the database driver to return numerical values with a precision specified by precisionPolicy.

The Oracle driver, for example, can retrieve numerical values as strings to prevent the loss of precision. If high precision doesn't matter, use this method to increase execution speed by bypassing string conversions.

Note: Drivers that don't support fetching numerical values with low precision will ignore the precision policy. You can use QSqlDriver::hasFeature() to find out whether a driver supports this feature.

Note: Setting the precision policy doesn't affect the currently active query. Call \l{exec()}{exec(QString)} or prepare() in order to activate the policy.

See also
QSql::NumericalPrecisionPolicy, QSqlDriver::numericalPrecisionPolicy, QSqlDatabase::numericalPrecisionPolicy

Definition at line 29 of file qsqlquery.h.

◆ positionalBindingEnabled

QSqlQuery::positionalBindingEnabled
readwrite
Since
6.8 This property enables or disables the positional \l {Approaches to Binding Values}{binding} for this query, depending on enable (default is true). Disabling positional bindings is useful if the query itself contains a '?' which must not be handled as a positional binding parameter but, for example, as a JSON operator for a PostgreSQL database.

This property will have no effect when the database has native support for positional bindings with question marks (see also \l{QSqlDriver::PositionalPlaceholders}).

Definition at line 28 of file qsqlquery.h.


The documentation for this class was generated from the following files: