Qt 4.8
Public Types | Public Functions | Properties | List of all members
QSqlQuery Class Reference

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

#include <qsqlquery.h>

Public Types

enum  BatchExecutionMode { ValuesAsRows, ValuesAsColumns }
 

Public Functions

void addBindValue (const QVariant &val, QSql::ParamType type=QSql::In)
 Adds the value val to the list of values when using positional value binding. More...
 
int at () const
 Returns the current internal position of the query. More...
 
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. More...
 
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. More...
 
QVariant boundValue (const QString &placeholder) const
 Returns the value for the placeholder. More...
 
QVariant boundValue (int pos) const
 Returns the value for the placeholder at position pos. More...
 
QMap< QString, QVariantboundValues () const
 Returns a map of the bound values. More...
 
void clear ()
 Clears the result set and releases any resources held by the query. More...
 
const QSqlDriverdriver () const
 Returns the database driver associated with the query. More...
 
bool exec (const QString &query)
 Executes the SQL in query. More...
 
bool exec ()
 Executes a previously prepared SQL query. More...
 
bool execBatch (BatchExecutionMode mode=ValuesAsRows)
 Executes a previously prepared SQL query in a batch. More...
 
QString executedQuery () const
 Returns the last query that was successfully executed. More...
 
void finish ()
 Instruct the database driver that no more data will be fetched from this query until it is re-executed. More...
 
bool first ()
 Retrieves the first record in the result, if available, and positions the query on the retrieved record. More...
 
bool isActive () const
 Returns true if the query is active. More...
 
bool isForwardOnly () const
 Returns true if you can only scroll forward through a result set; otherwise returns false. More...
 
bool isNull (int field) const
 Returns true if the query is active and positioned on a valid record and the field is NULL; otherwise returns false. More...
 
bool isSelect () const
 Returns true if the current query is a SELECT statement; otherwise returns false. More...
 
bool isValid () const
 Returns true if the query is currently positioned on a valid record; otherwise returns false. More...
 
bool last ()
 Retrieves the last record in the result, if available, and positions the query on the retrieved record. More...
 
QSqlError lastError () const
 Returns error information about the last error (if any) that occurred with this query. More...
 
QVariant lastInsertId () const
 Returns the object ID of the most recent inserted row if the database supports it. More...
 
QString lastQuery () const
 Returns the text of the current query being used, or an empty string if there is no current query text. More...
 
bool next ()
 Retrieves the next record in the result, if available, and positions the query on the retrieved record. More...
 
bool nextResult ()
 Discards the current result set and navigates to the next if available. More...
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy () const
 Returns the current precision policy. More...
 
int numRowsAffected () const
 Returns the number of rows affected by the result's SQL statement, or -1 if it cannot be determined. More...
 
QSqlQueryoperator= (const QSqlQuery &other)
 Assigns other to this object. More...
 
bool prepare (const QString &query)
 Prepares the SQL query query for execution. More...
 
bool previous ()
 Retrieves the previous record in the result, if available, and positions the query on the retrieved record. More...
 
 QSqlQuery (QSqlResult *r)
 Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database. More...
 
 QSqlQuery (const QString &query=QString(), QSqlDatabase db=QSqlDatabase())
 Constructs a QSqlQuery object using the SQL query and the database db. More...
 
 QSqlQuery (QSqlDatabase db)
 Constructs a QSqlQuery object using the database db. More...
 
 QSqlQuery (const QSqlQuery &other)
 Constructs a copy of other. More...
 
QSqlRecord record () const
 Returns a QSqlRecord containing the field information for the current query. More...
 
const QSqlResultresult () const
 Returns the result associated with the query. More...
 
bool seek (int i, bool relative=false)
 Retrieves the record at position index, if available, and positions the query on the retrieved record. More...
 
void setForwardOnly (bool forward)
 Sets forward only mode to forward. More...
 
void setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy)
 Instruct the database driver to return numerical values with a precision specified by precisionPolicy. More...
 
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. More...
 
QVariant value (int i) const
 Returns the value of field index in the current record. More...
 
 ~QSqlQuery ()
 Destroys the object and frees any allocated resources. More...
 

Properties

QSqlQueryPrivated
 

Detailed Description

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

Attention
Module: QtSql

QSqlQuery encapsulates the functionality involved in creating, navigating and retrieving data from SQL queries which are executed on a 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 QSqlDatabase::commit() or QSqlDatabase::rollback(), the commit or rollback will fail. See isActive() for details.

Navigating records is performed with the following functions:

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().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 (a map) using boundValues().

Approaches to Binding Values

Below we present the same example using each of the four different binding approaches, as well as one example of binding values to a stored procedure.

Named binding using named placeholders:

QSqlQuery query;
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();

Positional binding using named placeholders:

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();

Binding values using positional placeholders (version 1):

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();

Binding values using positional placeholders (version 2):

QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Bart");
query.addBindValue("Simpson");
query.exec();

Binding values to a stored procedure:

This code calls a stored procedure called AsciiToInt(), passing it a character through its in parameter, and taking its result in the out parameter.

QSqlQuery query;
query.prepare("CALL AsciiToInt(?, ?)");
query.bindValue(0, "A");
query.bindValue(1, 0, QSql::Out);
query.exec();
int i = query.boundValue(1).toInt(); // i is 65

Note that unbound parameters will retain their values.

Stored procedures that uses the return statement to return values, or return multiple result sets, are not fully supported. For specific details see SQL Database Drivers.

Warning
You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.
See also
QSqlDatabase, QSqlQueryModel, QSqlTableModel, QVariant

Definition at line 63 of file qsqlquery.h.

Enumerations

◆ BatchExecutionMode

  • ValuesAsRows - Updates multiple rows. Treats every entry in a QVariantList as a value for updating the next row.
  • 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 107 of file qsqlquery.h.

Constructors and Destructors

◆ QSqlQuery() [1/4]

QSqlQuery::QSqlQuery ( QSqlResult r)

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

Definition at line 236 of file qsqlquery.cpp.

237 {
238  d = new QSqlQueryPrivate(result);
239 }
const QSqlResult * result() const
Returns the result associated with the query.
Definition: qsqlquery.cpp:450
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ QSqlQuery() [2/4]

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

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 284 of file qsqlquery.cpp.

285 {
287  qInit(this, query, db);
288 }
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
static void qInit(QSqlQuery *q, const QString &query, QSqlDatabase db)
Definition: qsqlquery.cpp:264
static QSqlQueryPrivate * shared_null()

◆ QSqlQuery() [3/4]

QSqlQuery::QSqlQuery ( 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 297 of file qsqlquery.cpp.

298 {
300  qInit(this, QString(), db);
301 }
The QString class provides a Unicode character string.
Definition: qstring.h:83
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
static void qInit(QSqlQuery *q, const QString &query, QSqlDatabase db)
Definition: qsqlquery.cpp:264
static QSqlQueryPrivate * shared_null()

◆ QSqlQuery() [4/4]

QSqlQuery::QSqlQuery ( const QSqlQuery other)

Constructs a copy of other.

Definition at line 255 of file qsqlquery.cpp.

256 {
257  d = other.d;
258  d->ref.ref();
259 }
bool ref()
Atomically increments the value of this QAtomicInt.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
QAtomicInt ref
Definition: qsqlquery.cpp:62

◆ ~QSqlQuery()

QSqlQuery::~QSqlQuery ( )

Destroys the object and frees any allocated resources.

Definition at line 245 of file qsqlquery.cpp.

246 {
247  if (!d->ref.deref())
248  delete d;
249 }
bool deref()
Atomically decrements the value of this QAtomicInt.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
QAtomicInt ref
Definition: qsqlquery.cpp:62

Functions

◆ 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(QVariant::String)} if you are binding a string.

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

Definition at line 1060 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::exec().

1061 {
1063 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
void addBindValue(const QVariant &val, QSql::ParamType type)
Binds the value val of parameter type paramType to the next available position in the current record ...
Definition: qsqlresult.cpp:784
static QByteArray paramType(const QByteArray &ptype, bool *out)

◆ 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 420 of file qsqlquery.cpp.

Referenced by QDeclarativeSqlQueryScriptClass::property(), and qmlsqldatabase_item().

421 {
422  return d->sqlResult->at();
423 }
int at() const
Returns the current (zero-based) row position of the result.
Definition: qsqlresult.cpp:306
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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(QVariant::String)} if you are binding a string.

Values cannot be bound to multiple locations in the query, eg:

INSERT INTO testtable (id, name, samename) VALUES (:id, :name, :name)

Binding to name will bind to the first :name, but not the second.

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

Definition at line 1030 of file qsqlquery.cpp.

Referenced by qmlsqldatabase_executeSql().

1033 {
1034  d->sqlResult->bindValue(placeholder, val, paramType);
1035 }
virtual void bindValue(int pos, const QVariant &val, QSql::ParamType type)
Binds the value val of parameter type paramType to position index in the current record (row)...
Definition: qsqlresult.cpp:727
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
static QByteArray paramType(const QByteArray &ptype, bool *out)

◆ 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 1043 of file qsqlquery.cpp.

1044 {
1045  d->sqlResult->bindValue(pos, val, paramType);
1046 }
virtual void bindValue(int pos, const QVariant &val, QSql::ParamType type)
Binds the value val of parameter type paramType to position index in the current record (row)...
Definition: qsqlresult.cpp:727
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
static QByteArray paramType(const QByteArray &ptype, bool *out)

◆ boundValue() [1/2]

QVariant QSqlQuery::boundValue ( const QString placeholder) const

Returns the value for the placeholder.

See also
boundValues() bindValue() addBindValue()

Definition at line 1070 of file qsqlquery.cpp.

1071 {
1072  return d->sqlResult->boundValue(placeholder);
1073 }
QVariant boundValue(const QString &placeholder) const
Returns the value bound by the given placeholder name in the current record (row).
Definition: qsqlresult.cpp:813
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ boundValue() [2/2]

QVariant QSqlQuery::boundValue ( int  pos) const

Returns the value for the placeholder at position pos.

Definition at line 1078 of file qsqlquery.cpp.

1079 {
1080  return d->sqlResult->boundValue(pos);
1081 }
QVariant boundValue(const QString &placeholder) const
Returns the value bound by the given placeholder name in the current record (row).
Definition: qsqlresult.cpp:813
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ boundValues()

QMap< QString, QVariant > QSqlQuery::boundValues ( ) const

Returns a map of the bound values.

With named binding, the bound values can be examined in the following ways:

QMapIterator<QString, QVariant> i(query.boundValues());
while (i.hasNext()) {
i.next();
cout << i.key().toAscii().data() << ": "
<< i.value().toString().toAscii().data() << endl;
}

With positional binding, the code becomes:

QList<QVariant> list = query.boundValues().values();
for (int i = 0; i < list.size(); ++i)
cout << i << ": " << list.at(i).toString().toAscii().data() << endl;
See also
boundValue() bindValue() addBindValue()

Definition at line 1097 of file qsqlquery.cpp.

1098 {
1100 
1102  for (int i = 0; i < values.count(); ++i)
1103  map[d->sqlResult->boundValueName(i)] = values.at(i);
1104  return map;
1105 }
QString boundValueName(int pos) const
Returns the name of the bound value at position index in the current record (row).
Definition: qsqlresult.cpp:905
QFuture< void > map(Sequence &sequence, MapFunction function)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
quint16 values[128]
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
QVector< QVariant > & boundValues() const
Returns a vector of the result&#39;s bound values for the current record (row).
Definition: qsqlresult.cpp:859

◆ clear()

void QSqlQuery::clear ( void  )

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 874 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::clear().

875 {
876  *this = QSqlQuery(driver()->createResult());
877 }
const QSqlDriver * driver() const
Returns the database driver associated with the query.
Definition: qsqlquery.cpp:441
QSqlQuery(QSqlResult *r)
Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database...
Definition: qsqlquery.cpp:236

◆ driver()

const QSqlDriver * QSqlQuery::driver ( ) const

Returns the database driver associated with the query.

Definition at line 441 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::exec(), and QSqlQueryModel::setQuery().

442 {
443  return d->sqlResult->driver();
444 }
const QSqlDriver * driver() const
Returns the driver associated with the result.
Definition: qsqlresult.cpp:389
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ exec() [1/2]

bool QSqlQuery::exec ( const QString query)

Executes the SQL in query.

Returns true and sets the query state to 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 statements is give, the function returns false.

Example:

QSqlQuery query;
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 355 of file qsqlquery.cpp.

Referenced by QPSQLDriverPrivate::appendTables(), QSQLiteDriver::beginTransaction(), QSQLiteDriver::commitTransaction(), QSqlTableModelPrivate::exec(), QSqlDatabase::exec(), QODBCDriver::open(), QIBaseDriver::primaryIndex(), QOCIDriver::primaryIndex(), QSQLite2Driver::primaryIndex(), QTDSDriver::primaryIndex(), QMYSQLDriver::primaryIndex(), QPSQLDriver::primaryIndex(), qExtractSecurityPolicyFromString(), qGetTableInfo(), qInit(), qmlsqldatabase_executeSql(), QIBaseResult::record(), QIBaseDriver::record(), QOCIDriver::record(), QSQLite2Driver::record(), QTDSDriver::record(), QPSQLDriver::record(), QSQLiteDriver::rollbackTransaction(), QIBaseDriver::tables(), QSQLiteDriver::tables(), QOCIDriver::tables(), QSQLite2Driver::tables(), QTDSDriver::tables(), QMYSQLDriver::tables(), and QPSQLDriver::tables().

356 {
357  if (d->ref != 1) {
358  bool fo = isForwardOnly();
359  *this = QSqlQuery(driver()->createResult());
361  setForwardOnly(fo);
362  } else {
363  d->sqlResult->clear();
364  d->sqlResult->setActive(false);
368  }
369  d->sqlResult->setQuery(query.trimmed());
370  if (!driver()->isOpen() || driver()->isOpenError()) {
371  qWarning("QSqlQuery::exec: database not open");
372  return false;
373  }
374  if (query.isEmpty()) {
375  qWarning("QSqlQuery::exec: empty query");
376  return false;
377  }
378 #ifdef QT_DEBUG_SQL
379  qDebug("\n QSqlQuery: %s", query.toLocal8Bit().constData());
380 #endif
381  return d->sqlResult->reset(query);
382 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
const QSqlDriver * driver() const
Returns the database driver associated with the query.
Definition: qsqlquery.cpp:441
QSqlQuery(QSqlResult *r)
Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database...
Definition: qsqlquery.cpp:236
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy() const
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
virtual void setLastError(const QSqlError &e)
This function is provided for derived classes to set the last error to error.
Definition: qsqlresult.cpp:417
void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy)
bool isOpenError() const
Returns true if the there was an error opening the database connection; otherwise returns false...
Definition: qsqldriver.cpp:192
Q_CORE_EXPORT void qDebug(const char *,...)
QString trimmed() const Q_REQUIRED_RESULT
Returns a string that has whitespace removed from the start and the end.
Definition: qstring.cpp:4506
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
void setForwardOnly(bool forward)
Sets forward only mode to forward.
Definition: qsqlquery.cpp:835
virtual bool reset(const QString &sqlquery)=0
Sets the result to use the SQL statement query for subsequent data retrieval.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
void clear()
Clears the entire result set and releases any associated resources.
Definition: qsqlresult.cpp:876
virtual void setActive(bool a)
This function is provided for derived classes to set the internal active state to active...
Definition: qsqlresult.cpp:402
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
virtual void setQuery(const QString &query)
Sets the current query for the result to query.
Definition: qsqlresult.cpp:282
QAtomicInt ref
Definition: qsqlquery.cpp:62

◆ exec() [2/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 943 of file qsqlquery.cpp.

944 {
946 
947  if (d->sqlResult->lastError().isValid())
949 
950  return d->sqlResult->exec();
951 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
virtual void setLastError(const QSqlError &e)
This function is provided for derived classes to set the last error to error.
Definition: qsqlresult.cpp:417
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual bool exec()
Executes the query, returning true if successful; otherwise returns false.
Definition: qsqlresult.cpp:675
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
QSqlError lastError() const
Returns the last error associated with the result.
Definition: qsqlresult.cpp:427
bool isValid() const
Returns true if an error is set, otherwise false.
Definition: qsqlerror.cpp:254
void resetBindCount()
Definition: qsqlresult.cpp:894

◆ execBatch()

bool QSqlQuery::execBatch ( BatchExecutionMode  mode = ValuesAsRows)

Executes a previously prepared SQL query in a batch.

Since
4.2

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(QVariant::String);
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

To bind NULL values, a null QVariant of the relevant type has to be added to the bound QVariantList; for example, {QVariant(QVariant::String)} 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 1005 of file qsqlquery.cpp.

1006 {
1007  return d->sqlResult->execBatch(mode == ValuesAsColumns);
1008 }
bool execBatch(bool arrayBind=false)
Executes a prepared query in batch mode if the driver supports it, otherwise emulates a batch executi...
Definition: qsqlresult.cpp:997
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 1119 of file qsqlquery.cpp.

1120 {
1121  return d->sqlResult->executedQuery();
1122 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QString executedQuery() const
Returns the query that was actually executed.
Definition: qsqlresult.cpp:889
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ finish()

void QSqlQuery::finish ( )

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

Since
4.3.2

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 1205 of file qsqlquery.cpp.

1206 {
1207  if (isActive()) {
1211  d->sqlResult->setActive(false);
1212  }
1213 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
virtual void setLastError(const QSqlError &e)
This function is provided for derived classes to set the last error to error.
Definition: qsqlresult.cpp:417
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
void detachFromResultSet()
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
virtual void setActive(bool a)
This function is provided for derived classes to set the internal active state to active...
Definition: qsqlresult.cpp:402

◆ 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 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 678 of file qsqlquery.cpp.

Referenced by QIBaseResult::record().

679 {
680  if (!isSelect() || !isActive())
681  return false;
682  if (isForwardOnly() && at() > QSql::BeforeFirstRow) {
683  qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
684  return false;
685  }
686  bool b = false;
687  b = d->sqlResult->fetchFirst();
688  return b;
689 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
virtual bool fetchFirst()=0
Positions the result to the first record (row 0) in the result.
bool isSelect() const
Returns true if the current query is a SELECT statement; otherwise returns false. ...
Definition: qsqlquery.cpp:795
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
int at() const
Returns the current internal position of the query.
Definition: qsqlquery.cpp:420

◆ isActive()

bool QSqlQuery::isActive ( ) const

Returns true if the query is active.

An active QSqlQuery is one that has been exec()'d successfully but not yet finished with. When you are finished with an active query, you can make 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 QSqlDatabase::commit() or a 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 785 of file qsqlquery.cpp.

Referenced by QMYSQLDriver::primaryIndex(), QPSQLDriver::primaryIndex(), QPSQLDriver::record(), QSqlTableModel::select(), QSqlQueryModel::setQuery(), and QSQLite2Driver::tables().

786 {
787  return d->sqlResult->isActive();
788 }
bool isActive() const
Returns true if the result has records to be retrieved; otherwise returns false.
Definition: qsqlresult.cpp:340
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ isForwardOnly()

bool QSqlQuery::isForwardOnly ( ) const

Returns true if you can only scroll forward through a result set; otherwise returns false.

See also
setForwardOnly(), next()

Definition at line 806 of file qsqlquery.cpp.

Referenced by QDeclarativeSqlQueryScriptClass::property(), and QSqlQueryModel::setQuery().

807 {
808  return d->sqlResult->isForwardOnly();
809 }
bool isForwardOnly() const
Returns true if you can only scroll forward through the result set; otherwise returns false...
Definition: qsqlresult.cpp:582
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ isNull()

bool QSqlQuery::isNull ( int  field) const

Returns true if the query is active and positioned on a valid record and the field is NULL; otherwise returns 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 323 of file qsqlquery.cpp.

Referenced by QOCIDriver::record().

324 {
325  if (d->sqlResult->isActive() && d->sqlResult->isValid())
326  return d->sqlResult->isNull(field);
327  return true;
328 }
bool isActive() const
Returns true if the result has records to be retrieved; otherwise returns false.
Definition: qsqlresult.cpp:340
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
bool isValid() const
Returns true if the result is positioned on a valid record (that is, the result is not positioned bef...
Definition: qsqlresult.cpp:320
virtual bool isNull(int i)=0
Returns true if the field at position index in the current row is null; otherwise returns false...

◆ isSelect()

bool QSqlQuery::isSelect ( ) const

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

Definition at line 795 of file qsqlquery.cpp.

796 {
797  return d->sqlResult->isSelect();
798 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
bool isSelect() const
Returns true if the current result is from a SELECT statement; otherwise returns false.
Definition: qsqlresult.cpp:379

◆ isValid()

bool QSqlQuery::isValid ( ) const

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

Definition at line 764 of file qsqlquery.cpp.

765 {
766  return d->sqlResult->isValid();
767 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
bool isValid() const
Returns true if the result is positioned on a valid record (that is, the result is not positioned bef...
Definition: qsqlresult.cpp:320

◆ 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 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 703 of file qsqlquery.cpp.

Referenced by QDeclarativeSqlQueryScriptClass::property().

704 {
705  if (!isSelect() || !isActive())
706  return false;
707  bool b = false;
708  b = d->sqlResult->fetchLast();
709  return b;
710 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
bool isSelect() const
Returns true if the current query is a SELECT statement; otherwise returns false. ...
Definition: qsqlquery.cpp:795
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual bool fetchLast()=0
Positions the result to the last record (last row) in the result.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 754 of file qsqlquery.cpp.

Referenced by QSQLiteDriver::beginTransaction(), QSQLiteDriver::commitTransaction(), QSqlTableModelPrivate::exec(), QSqlTableModelPrivate::primaryValues(), qmlsqldatabase_executeSql(), QSQLiteDriver::rollbackTransaction(), and QSqlQueryModel::setQuery().

755 {
756  return d->sqlResult->lastError();
757 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
QSqlError lastError() const
Returns the last error associated with the result.
Definition: qsqlresult.cpp:427

◆ 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 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 1148 of file qsqlquery.cpp.

Referenced by qmlsqldatabase_executeSql().

1149 {
1150  return d->sqlResult->lastInsertId();
1151 }
virtual QVariant lastInsertId() const
Returns the object ID of the most recent inserted row if the database supports it.
Definition: qsqlresult.cpp:955
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 432 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::exec().

433 {
434  return d->sqlResult->lastQuery();
435 }
QString lastQuery() const
Returns the current SQL query text, or an empty string if there isn&#39;t one.
Definition: qsqlresult.cpp:294
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 active state and isSelect() must return true before calling this function or it will do nothing and return false.

The following rules apply:

  • 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.

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 594 of file qsqlquery.cpp.

Referenced by QPSQLDriverPrivate::appendTables(), QSqlQueryModelPrivate::prefetch(), QIBaseDriver::primaryIndex(), QOCIDriver::primaryIndex(), QSQLite2Driver::primaryIndex(), QTDSDriver::primaryIndex(), QMYSQLDriver::primaryIndex(), QPSQLDriver::primaryIndex(), qExtractSecurityPolicyFromString(), qGetTableInfo(), QIBaseDriver::record(), QOCIDriver::record(), QTDSDriver::record(), QPSQLDriver::record(), QIBaseDriver::tables(), QSQLiteDriver::tables(), QOCIDriver::tables(), QSQLite2Driver::tables(), QTDSDriver::tables(), QMYSQLDriver::tables(), and QPSQLDriver::tables().

595 {
596  if (!isSelect() || !isActive())
597  return false;
598  bool b = false;
599  switch (at()) {
601  b = d->sqlResult->fetchFirst();
602  return b;
603  case QSql::AfterLastRow:
604  return false;
605  default:
606  if (!d->sqlResult->fetchNext()) {
608  return false;
609  }
610  return true;
611  }
612 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
virtual bool fetchFirst()=0
Positions the result to the first record (row 0) in the result.
bool isSelect() const
Returns true if the current query is a SELECT statement; otherwise returns false. ...
Definition: qsqlquery.cpp:795
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
virtual bool fetchNext()
Positions the result to the next available record (row) in the result.
Definition: qsqlresult.cpp:555
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
int at() const
Returns the current internal position of the query.
Definition: qsqlquery.cpp:420

◆ nextResult()

bool QSqlQuery::nextResult ( )

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

Since
4.4

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() setForwardOnly() next() isSelect() numRowsAffected() isActive() lastError()

Definition at line 1248 of file qsqlquery.cpp.

1249 {
1250  if (isActive())
1251  return d->sqlResult->nextResult();
1252  return false;
1253 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
bool nextResult()
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ numericalPrecisionPolicy()

QSql::NumericalPrecisionPolicy QSqlQuery::numericalPrecisionPolicy ( ) const

Returns the current precision policy.

See also
QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy()

Definition at line 1184 of file qsqlquery.cpp.

Referenced by QOCIDriver::primaryIndex(), and QOCIDriver::record().

1185 {
1187 }
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy() const
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 active, -1 is returned.

See also
size() QSqlDriver::hasFeature()

Definition at line 740 of file qsqlquery.cpp.

Referenced by qmlsqldatabase_executeSql().

741 {
742  if (isActive())
743  return d->sqlResult->numRowsAffected();
744  return -1;
745 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual int numRowsAffected()=0
Returns the number of rows affected by the last query executed, or -1 if it cannot be determined or i...
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ operator=()

QSqlQuery & QSqlQuery::operator= ( const QSqlQuery other)

Assigns other to this object.

Definition at line 308 of file qsqlquery.cpp.

309 {
310  qAtomicAssign(d, other.d);
311  return *this;
312 }
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
void qAtomicAssign(T *&d, T *x)
This is a helper for the assignment operators of implicitly shared classes.
Definition: qatomic.h:195

◆ 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 QSqlQuery examples{Detailed Description} for examples.

Portability note: 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.

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

Example:

QSqlQuery query;
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 903 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::exec(), and qmlsqldatabase_executeSql().

904 {
905  if (d->ref != 1) {
906  bool fo = isForwardOnly();
907  *this = QSqlQuery(driver()->createResult());
908  setForwardOnly(fo);
910  } else {
911  d->sqlResult->setActive(false);
915  }
916  if (!driver()) {
917  qWarning("QSqlQuery::prepare: no driver");
918  return false;
919  }
920  if (!driver()->isOpen() || driver()->isOpenError()) {
921  qWarning("QSqlQuery::prepare: database not open");
922  return false;
923  }
924  if (query.isEmpty()) {
925  qWarning("QSqlQuery::prepare: empty query");
926  return false;
927  }
928 #ifdef QT_DEBUG_SQL
929  qDebug("\n QSqlQuery::prepare: %s", query.toLocal8Bit().constData());
930 #endif
931  return d->sqlResult->savePrepare(query);
932 }
The QSqlError class provides SQL database error information.
Definition: qsqlerror.h:53
const QSqlDriver * driver() const
Returns the database driver associated with the query.
Definition: qsqlquery.cpp:441
QSqlQuery(QSqlResult *r)
Constructs a QSqlQuery object which uses the QSqlResult result to communicate with a database...
Definition: qsqlquery.cpp:236
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy() const
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
virtual void setLastError(const QSqlError &e)
This function is provided for derived classes to set the last error to error.
Definition: qsqlresult.cpp:417
void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy)
Q_CORE_EXPORT void qDebug(const char *,...)
virtual bool savePrepare(const QString &sqlquery)
Prepares the given query, using the underlying database functionality where possible.
Definition: qsqlresult.cpp:615
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
void setForwardOnly(bool forward)
Sets forward only mode to forward.
Definition: qsqlquery.cpp:835
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
virtual void setActive(bool a)
This function is provided for derived classes to set the internal active state to active...
Definition: qsqlresult.cpp:402
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
QAtomicInt ref
Definition: qsqlquery.cpp:62

◆ 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 active state and isSelect() must return true before calling this function or it will do nothing and return false.

The following rules apply:

  • 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.

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 643 of file qsqlquery.cpp.

644 {
645  if (!isSelect() || !isActive())
646  return false;
647  if (isForwardOnly()) {
648  qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
649  return false;
650  }
651 
652  bool b = false;
653  switch (at()) {
655  return false;
656  case QSql::AfterLastRow:
657  b = d->sqlResult->fetchLast();
658  return b;
659  default:
660  if (!d->sqlResult->fetchPrevious()) {
662  return false;
663  }
664  return true;
665  }
666 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
bool isSelect() const
Returns true if the current query is a SELECT statement; otherwise returns false. ...
Definition: qsqlquery.cpp:795
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual bool fetchLast()=0
Positions the result to the last record (last row) in the result.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
virtual bool fetchPrevious()
Positions the result to the previous record (row) in the result.
Definition: qsqlresult.cpp:571
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
int at() const
Returns the current internal position of the query.
Definition: qsqlquery.cpp:420

◆ 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 858 of file qsqlquery.cpp.

Referenced by QSqlDatabase::isValid(), qmlsqldatabase_item(), QSQLite2Driver::record(), and QSqlQueryModel::setQuery().

859 {
860  QSqlRecord rec = d->sqlResult->record();
861 
862  if (isValid()) {
863  for (int i = 0; i < rec.count(); ++i)
864  rec.setValue(i, value(i));
865  }
866  return rec;
867 }
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
virtual QSqlRecord record() const
Returns the current record if the query is active; otherwise returns an empty QSqlRecord.
Definition: qsqlresult.cpp:936
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
int count() const
Returns the number of fields in the record.
Definition: qsqlrecord.cpp:573
void setValue(int i, const QVariant &val)
Sets the value of the field at position index to val.
Definition: qsqlrecord.cpp:585
QVariant value(int i) const
Returns the value of field index in the current record.
Definition: qsqlquery.cpp:403
bool isValid() const
Returns true if the query is currently positioned on a valid record; otherwise returns false...
Definition: qsqlquery.cpp:764

◆ result()

const QSqlResult * QSqlQuery::result ( ) const

Returns the result associated with the query.

Definition at line 450 of file qsqlquery.cpp.

Referenced by QSqlTableModelPrivate::exec().

451 {
452  return d->sqlResult;
453 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 active state and isSelect() must return true before calling this function.

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

  • 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.

If relative is true, the following rules apply:

  • If the result is currently positioned before the first record or on the first record, and index is negative, there is no change, and false is returned.

  • If the result is currently located after the last record, and index is positive, there is no change, and false is returned.

  • 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.

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

Definition at line 502 of file qsqlquery.cpp.

Referenced by QSqlQueryModelPrivate::prefetch(), QSqlTableModelPrivate::primaryValues(), and qmlsqldatabase_item().

503 {
504  if (!isSelect() || !isActive())
505  return false;
506  int actualIdx;
507  if (!relative) { // arbitrary seek
508  if (index < 0) {
510  return false;
511  }
512  actualIdx = index;
513  } else {
514  switch (at()) { // relative seek
516  if (index > 0)
517  actualIdx = index;
518  else {
519  return false;
520  }
521  break;
522  case QSql::AfterLastRow:
523  if (index < 0) {
524  d->sqlResult->fetchLast();
525  actualIdx = at() + index;
526  } else {
527  return false;
528  }
529  break;
530  default:
531  if ((at() + index) < 0) {
533  return false;
534  }
535  actualIdx = at() + index;
536  break;
537  }
538  }
539  // let drivers optimize
540  if (isForwardOnly() && actualIdx < at()) {
541  qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
542  return false;
543  }
544  if (actualIdx == (at() + 1) && at() != QSql::BeforeFirstRow) {
545  if (!d->sqlResult->fetchNext()) {
547  return false;
548  }
549  return true;
550  }
551  if (actualIdx == (at() - 1)) {
552  if (!d->sqlResult->fetchPrevious()) {
554  return false;
555  }
556  return true;
557  }
558  if (!d->sqlResult->fetch(actualIdx)) {
560  return false;
561  }
562  return true;
563 }
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
bool isSelect() const
Returns true if the current query is a SELECT statement; otherwise returns false. ...
Definition: qsqlquery.cpp:795
virtual void setAt(int at)
This function is provided for derived classes to set the internal (zero-based) row position to index...
Definition: qsqlresult.cpp:352
virtual bool fetchNext()
Positions the result to the next available record (row) in the result.
Definition: qsqlresult.cpp:555
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual bool fetchLast()=0
Positions the result to the last record (last row) in the result.
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
virtual bool fetchPrevious()
Positions the result to the previous record (row) in the result.
Definition: qsqlresult.cpp:571
quint16 index
bool isForwardOnly() const
Returns true if you can only scroll forward through a result set; otherwise returns false...
Definition: qsqlquery.cpp:806
virtual bool fetch(int i)=0
Positions the result to an arbitrary (zero-based) row index.
int at() const
Returns the current internal position of the query.
Definition: qsqlquery.cpp:420

◆ setForwardOnly()

void QSqlQuery::setForwardOnly ( bool  forward)

Sets forward only mode to forward.

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.
See also
isForwardOnly(), next(), seek(), QSqlResult::setForwardOnly()

Definition at line 835 of file qsqlquery.cpp.

Referenced by QIBaseDriver::primaryIndex(), QSQLiteDriver::primaryIndex(), QOCIDriver::primaryIndex(), QSQLite2Driver::primaryIndex(), QTDSDriver::primaryIndex(), qExtractSecurityPolicyFromString(), QIBaseResult::record(), QIBaseDriver::record(), QSQLiteDriver::record(), QOCIDriver::record(), QSQLite2Driver::record(), QTDSDriver::record(), QDeclarativeSqlQueryScriptClass::setProperty(), QIBaseDriver::tables(), QSQLiteDriver::tables(), QOCIDriver::tables(), QSQLite2Driver::tables(), QTDSDriver::tables(), and QPSQLDriver::tables().

836 {
837  d->sqlResult->setForwardOnly(forward);
838 }
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
virtual void setForwardOnly(bool forward)
Sets forward only mode to forward.
Definition: qsqlresult.cpp:603
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ setNumericalPrecisionPolicy()

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

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 exec(QString) or prepare() in order to activate the policy.

See also
QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy()

Definition at line 1174 of file qsqlquery.cpp.

1175 {
1176  d->sqlResult->setNumericalPrecisionPolicy(precisionPolicy);
1177 }
void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123

◆ 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 724 of file qsqlquery.cpp.

Referenced by QDeclarativeSqlQueryScriptClass::property().

725 {
727  return d->sqlResult->size();
728  return -1;
729 }
const QSqlDriver * driver() const
Returns the driver associated with the result.
Definition: qsqlresult.cpp:389
virtual bool hasFeature(DriverFeature f) const =0
Returns true if the driver supports feature feature; otherwise returns false.
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
virtual int size()=0
Returns the size of the SELECT result, or -1 if it cannot be determined or if the query is not a SELE...

◆ value()

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

SELECT forename, surname FROM people;

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 403 of file qsqlquery.cpp.

Referenced by QPSQLDriverPrivate::appendTables(), QIBaseDriver::primaryIndex(), QOCIDriver::primaryIndex(), QSQLite2Driver::primaryIndex(), QTDSDriver::primaryIndex(), QMYSQLDriver::primaryIndex(), QPSQLDriver::primaryIndex(), QSqlTableModelPrivate::primaryValues(), qExtractSecurityPolicyFromString(), qGetTableInfo(), QIBaseResult::record(), QIBaseDriver::record(), QOCIDriver::record(), QTDSDriver::record(), QPSQLDriver::record(), QIBaseDriver::tables(), QSQLiteDriver::tables(), QOCIDriver::tables(), QSQLite2Driver::tables(), QTDSDriver::tables(), QMYSQLDriver::tables(), and QPSQLDriver::tables().

404 {
405  if (isActive() && isValid() && (index > QSql::BeforeFirstRow))
406  return d->sqlResult->data(index);
407  qWarning("QSqlQuery::value: not positioned on a valid record");
408  return QVariant();
409 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
bool isActive() const
Returns true if the query is active.
Definition: qsqlquery.cpp:785
virtual QVariant data(int i)=0
Returns the data for field index in the current row as a QVariant.
Q_CORE_EXPORT void qWarning(const char *,...)
QSqlResult * sqlResult
Definition: qsqlquery.cpp:63
QSqlQueryPrivate * d
Definition: qsqlquery.h:123
quint16 index
bool isValid() const
Returns true if the query is currently positioned on a valid record; otherwise returns false...
Definition: qsqlquery.cpp:764

Properties

◆ d

QSqlQueryPrivate* QSqlQuery::d
private

Definition at line 123 of file qsqlquery.h.

Referenced by operator=(), and QSqlQuery().


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