QSqlQuery(3qt)
π QSqlQuery π β the QSqlQuery(3qt) manual, bestie edition
okay so. you wanna talk to a database from Qt. this is the class that does it. no cap.
β¨ NAME β¨
QSqlQuery β bestie, it's literally the way to execute and manipulate SQL statements. that's the whole vibe. π
πΈ SYNOPSIS πΈ
#include <qsqlquery.h>
Inherited by QSqlCursor. (yes she has children. main character energy. π)
π«Ά Public Members π«Ά
QSqlQuery ( QSqlResult * r )QSqlQuery ( const QString & query = QString::null, QSqlDatabase * db = 0 )explicit QSqlQuery ( QSqlDatabase * db )QSqlQuery ( const QSqlQuery & other )QSqlQuery & operator= ( const QSqlQuery & other )virtual ~QSqlQuery ()bool isValid () constbool isActive () constbool isNull ( int field ) constint at () constQString lastQuery () constint numRowsAffected () constQSqlError lastError () constbool isSelect () constint size () constconst QSqlDriver * driver () constconst QSqlResult * result () constbool isForwardOnly () constvoid setForwardOnly ( bool forward )virtual bool exec ( const QString & query )virtual QVariant value ( int i ) constvirtual bool seek ( int i, bool relative = FALSE )virtual bool next ()virtual bool prev ()virtual bool first ()virtual bool last ()bool exec ()bool prepare ( const QString & query )void bindValue ( const QString & placeholder, const QVariant & val )void bindValue ( int pos, const QVariant & val )void addBindValue ( const QVariant & val )void bindValue ( const QString & placeholder, const QVariant & val, QSql::ParameterType type )void bindValue ( int pos, const QVariant & val, QSql::ParameterType type )void addBindValue ( const QVariant & val, QSql::ParameterType type )QVariant boundValue ( const QString & placeholder ) constQVariant boundValue ( int pos ) constQMap<QString, QVariant> boundValues () constQString executedQuery () const
π Protected Members π
virtual void beforeSeek ()virtual void afterSeek ()
π¦ DESCRIPTION π¦
The QSqlQuery class provides a means of executing and manipulating SQL statements. say it with me. she runs your SQL and she handles what comes back. π
QSqlQuery encapsulates the functionality involved in creating, navigating and retrieving data from SQL queries which are executed on a QSqlDatabase. She can run DML (data manipulation language) statements β like SELECT, INSERT, UPDATE and DELETE β and also DDL (data definition language) statements, like CREATE TABLE. She can also run database-specific commands that aren't standard SQL (for example SET DATESTYLE=ISO for PostgreSQL). versatile queen. π
Successfully executed SQL statements set the query's state to active (isActive() returns TRUE); otherwise the query's state gets set to inactive. Either way, when you execute a new SQL statement, the query is positioned on an invalid record β so an active query has to be navigated to a valid record (so that isValid() returns TRUE) before you can retrieve values. don't skip that step bestie, it's giving undefined-nothing. π
Navigating records is done with these functions:
next()prev()first()last()seek(int)
These let the programmer move forward, backward, or arbitrarily through the records the query returned. If you only need to move forward through the results β like using next() or using seek() with a positive offset β you can use setForwardOnly() and save a significant amount of memory overhead. obsessed with efficiency. β¨ 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 name FROM customer" );
while ( query.next() ) {
QString name = query.value(0).toString();
doSomething( name );
}
To access the data returned by a query, use the value() method. Each field in the data returned by a SELECT statement is accessed by passing the field's position in the statement, starting from 0. Information about the fields can be obtained via QSqlDatabase::record(). For the sake of efficiency there are no functions to access a field by name. (The QSqlCursor class provides a higher-level interface with field access by name and automatic SQL generation.) iykyk. π
QSqlQuery supports prepared query execution and the binding of parameter values to placeholders. Some databases don't support these features, so for them 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. The exception is positional binding using named placeholders, which requires that the database supports prepared queries. β οΈ
Oracle databases identify placeholders by using a colon-name syntax, e.g :name. ODBC simply uses ? characters. Qt supports both syntaxes (although you can't mix them in the same query). pick a lane bestie, one or the other. π
Below we present the same example using each of the four different binding approaches.
Named binding using named placeholders
QSqlQuery query;
query.prepare( "INSERT INTO atable (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 atable (id, forename, surname) "
"VALUES (:id, :forename, :surname)" );
query.bindValue( 0, 1001 );
query.bindValue( 1, "Bart" );
query.bindValue( 2, "Simpson" );
query.exec();
Note: Using positional binding with named placeholders will only work if the database supports prepared queries. This can be checked withQSqlDriver::hasFeature()usingQSqlDriver::PreparedQueriesas argument for driver feature.
Binding values using positional placeholders #1
QSqlQuery query;
query.prepare( "INSERT INTO atable (id, forename, surname) "
"VALUES (?, ?, ?)" );
query.bindValue( 0, 1001 );
query.bindValue( 1, "Bart" );
query.bindValue( 2, "Simpson" );
query.exec();
Binding values using positional placeholders #2
query.prepare( "INSERT INTO atable (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.
See also QSqlDatabase, QSqlCursor, QVariant, and Database Classes. π«Ά
π MEMBER FUNCTION DOCUMENTATION π
QSqlQuery::QSqlQuery ( QSqlResult * r )
Creates a QSqlQuery object which uses the QSqlResult r to communicate with a database. she needs her lil translator. β¨
QSqlQuery::QSqlQuery ( const QString & query = QString::null, QSqlDatabase * db = 0 )
Creates a QSqlQuery object using the SQL query and the database db. If db is 0, (the default), the application's default database is used. If query is not a null string, it will be executed. π₯
See also QSqlDatabase.
explicit QSqlQuery::QSqlQuery ( QSqlDatabase * db )
Creates a QSqlQuery object using the database db. If db is 0, the application's default database is used.
See also QSqlDatabase.
QSqlQuery::QSqlQuery ( const QSqlQuery & other )
Constructs a copy of other. twin behaviour. π
QSqlQuery::~QSqlQuery () [virtual]
Destroys the object and frees any allocated resources. she's done, let her rest. π§
void QSqlQuery::addBindValue ( const QVariant & val, QSql::ParameterType type )
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 type is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.
See also bindValue(), prepare(), and exec().
void QSqlQuery::addBindValue ( const QVariant & val )
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Binds the placeholder with type QSql::In.
void QSqlQuery::afterSeek () [virtual protected]
Protected virtual function called after the internal record pointer is moved to a new record. The default implementation does nothing. (she's just there for the vibes. πΈ)
int QSqlQuery::at () const
Returns the current internal position of the query. The first record is at position zero. If the position is invalid, a QSql::Location will be returned indicating the invalid position.
See also prev(), next(), first(), last(), seek(), isActive(), and isValid().
Example: sql/overview/navigating/main.cpp.
void QSqlQuery::beforeSeek () [virtual protected]
Protected virtual function called before the internal record pointer is moved to a new record. The default implementation does nothing.
void QSqlQuery::bindValue ( const QString & placeholder, const QVariant & val, QSql::ParameterType type )
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 type is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.
See also addBindValue(), prepare(), and exec().
void QSqlQuery::bindValue ( const QString & placeholder, const QVariant & val )
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Binds the placeholder with type QSql::In.
void QSqlQuery::bindValue ( int pos, const QVariant & val )
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Binds the placeholder at position pos with type QSql::In.
void QSqlQuery::bindValue ( int pos, const QVariant & val, QSql::ParameterType type )
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Set the placeholder in position pos to be bound to value val in the prepared statement. Field numbering starts at 0. If type is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.
See also addBindValue(), prepare(), and exec().
QVariant QSqlQuery::boundValue ( const QString & placeholder ) const
Returns the value for the placeholder. π
QVariant QSqlQuery::boundValue ( int pos ) const
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Returns the value for the placeholder at position pos.
QMap<QString, QVariant> QSqlQuery::boundValues () const π
okay so this one hands you back a map of all ur bound values. that's it, that's the vibe. it's giving "receipts for everything u bound" β¨
here's how u actually peek at them, bestie:
QSqlQuery query;
...
// Examine the bound values - bound using named binding
QMap<QString, QVariant>::ConstIterator it;
QMap<QString, QVariant> vals = query.boundValues();
for ( it = vals.begin(); it != vals.end(); ++it )
qWarning( "Placeholder: " + it.key() + ", Value: " + (*it).toString() );
...
// Examine the bound values - bound using positional binding
QValueList<QVariant>::ConstIterator it;
QValueList<QVariant> list = query.boundValues().values();
int i = 0;
for ( it = list.begin(); it != list.end(); ++it )
qWarning( "Placeholder pos: %d, Value: " + (*it).toString(), i++ );
...
like, named binding = u iterate the QMap and grab it.key() for the placeholder. positional = u call .values() and get a QValueList u can walk with an int counter. iconic. π
const QSqlDriver * QSqlQuery::driver () const π
returns the database driver that's riding along with this query. ur query's plus-one, basically. π
bool QSqlQuery::exec ( const QString & query ) [virtual] π₯
this is THE one. it executes the SQL sitting in query.
- returns
TRUEand sets the query state to active if it worked - returns
FALSEand sets the query state to inactive if it did not
the query string has to use syntax that's appropriate for the SQL database u are actually querying β like, standard SQL, yk? don't come with Postgres dialect to a MySQL party. π
after the query executes, the query is positioned on an invalid record, and u must navigate to a valid record before u can retrieve data values, e.g. using next().
also important: the last error for this query is reset when exec() is called. fresh slate, no grudges. β¨
See also isActive(), isValid(), next(), prev(), first(), last(), and seek().
Examples:
bool QSqlQuery::exec () πΈ
this is an overloaded member function, provided for convenience β it behaves essentially like the above function. same energy, no arguments. π
it executes a previously prepared SQL query. returns TRUE if the query executed successfully; otherwise returns FALSE.
See also prepare(), bindValue(), and addBindValue().
QString QSqlQuery::executedQuery () const π
returns the last query that was executed.
in most cases this returns the same thing as lastQuery(). but here's the tea: if a prepared query with placeholders gets executed on a DBMS that does not support it, the preparation of that query is emulated. the placeholders in the original query get replaced with their bound values to form a new query β and this function returns that modified query. super useful for debugging purposes. π΅οΈβοΈ
See also lastQuery().
bool QSqlQuery::first () [virtual] β
grabs the first record in the result, if available, and positions the query on the retrieved record.
heads up bestie: the result must be in an active state andisSelect()must returnTRUEbefore u call this, or it will do nothing and returnFALSE. it's giving strict bouncer. π«
returns TRUE if successful. if unsuccessful, the query position is set to an invalid position and FALSE is returned.
See also next(), prev(), last(), seek(), at(), isActive(), and isValid().
Example: sql/overview/navigating/main.cpp.
bool QSqlQuery::isActive () const π¦
returns TRUE if the query is currently active; otherwise returns FALSE. that's the whole thing. main character check-in. π
Examples:
bool QSqlQuery::isForwardOnly () const β‘οΈ
returns TRUE if u can only scroll forward through a result set; otherwise returns FALSE.
See also setForwardOnly().
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.
ngl, for some drivers isNull() will not return accurate information until after an attempt is made to retrieve data. so don't trust it before u poke it. π
See also isActive(), isValid(), and value().
bool QSqlQuery::isSelect () const π
returns TRUE if the current query is a SELECT statement; otherwise returns FALSE. yes queen, are u a select or not. π
bool QSqlQuery::isValid () const β
returns TRUE if the query is currently positioned on a valid record; otherwise returns FALSE.
bool QSqlQuery::last () [virtual] π
grabs the last record in the result, if available, and positions the query on the retrieved record.
same rule asfirst(): the result must be in an active state andisSelect()must returnTRUEbefore u call this function, or it will do nothing and returnFALSE.
returns TRUE if successful. if unsuccessful, the query position is set to an invalid position and FALSE is returned.
See also next(), prev(), first(), seek(), at(), isActive(), and isValid().
Example: sql/overview/navigating/main.cpp.
QSqlError QSqlQuery::lastError () const π
returns error information about the last error (if any) that occurred. the receipts for when things went sideways.
See also QSqlError.
QString QSqlQuery::lastQuery () const π
returns the text of the current query being used, or QString::null if there is no current query text.
See also executedQuery().
bool QSqlQuery::next () [virtual] π
grabs the next record in the result, if available, and positions the query on the retrieved record.
once again: the result must be in an active state andisSelect()must returnTRUEbefore calling this, or it will do nothing and returnFALSE.
the following rules apply, bestie, write these down π:
- 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
FALSEis 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
FALSEis returned. if the record is successfully retrieved,TRUEis returned.
See also prev(), first(), last(), seek(), at(), isActive(), and isValid().
Examples:
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 forSELECTstatements, the value is undefined β go look atsize()instead, bestie, don't do this to urself.
if the query is not active (isActive() returns FALSE), -1 is returned.
See also size() and QSqlDriver::hasFeature().
Examples:
QSqlQuery & QSqlQuery::operator= ( const QSqlQuery & other ) π«Ά
assigns other to the query. copy-paste but make it official. π
bool QSqlQuery::prepare ( const QString & query ) π
prepares the SQL query query for execution. the query may contain placeholders for binding values.
both of these are supported:
- Oracle style colon-name (e.g.
:surname) - ODBC style (e.g.
?)
but they cannot be mixed in the same query. pick a lane, queen. π«β¨
see the Description for examples.
See also exec(), bindValue(), and addBindValue().
bool QSqlQuery::prev () [virtual] π
grabs the previous record in the result, if available, and positions the query on the retrieved record.
yep, u guessed it: the result must be in an active state andisSelect()must returnTRUEbefore calling this function, or it will do nothing and returnFALSE.
the rules, incoming π:
- if the result is currently located before the first record, there is no change and
FALSEis 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
FALSEis returned. if the record is successfully retrieved,TRUEis returned.
See also next(), first(), last(), seek(), at(), isActive(), and isValid().
const QSqlResult * QSqlQuery::result () const π¦
returns the result associated with the query. the whole entire result. no cap.
bool QSqlQuery::seek ( int i, bool relative = FALSE ) [virtual] π―
retrieves the record at position (offset) i, 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 andisSelect()must returnTRUEbefore calling this function. non-negotiable. π
if relative is FALSE (the default), these rules apply:
- if
iis negative, the result is positioned before the first record andFALSEis returned. - otherwise, an attempt is made to move to the record at position
i. if the record at positionicould not be retrieved, the result is positioned after the last record andFALSEis returned. if the record is successfully retrieved,TRUEis returned.
if relative is TRUE, these rules apply:
- if the result is currently positioned before the first record or on the first record, and
iis negative, there is no change, andFALSEis returned. - if the result is currently located after the last record, and
iis positive, there is no change, andFALSEis returned. - if the result is currently located somewhere in the middle, and the relative offset
imoves the result below zero, the result is positioned before the first record andFALSEis returned. - otherwise, an attempt is made to move to the record
irecords ahead of the current record (orirecords behind the current record ifiis negative). if the record at offseticould not be retrieved, the result is positioned after the last record ifi >= 0, (or before the first record ifiis negative), andFALSEis returned. if the record is successfully retrieved,TRUEis returned.
See also next(), prev(), first(), last(), at(), isActive(), and isValid().
Example: sql/overview/navigating/main.cpp.
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 needs far less memory since results do not need to be cached. it's giving low-maintenance. π
forward only mode is off by default.
forward only mode cannot be used with data aware widgets like QDataTable, since they must be able to scroll backward as well as forward. so if ur using those, this mode is not for u, sorry bestie. π
See also isForwardOnly(), next(), and seek().
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-SELECTstatements (isSelect()returnsFALSE),size()will return-1. and if the query is not active (isActive()returnsFALSE),-1is returned too. so many-1s, it's giving "no data, no clue". π
to determine the number of rows affected by a non-SELECT statement, use numRowsAffected().
See also isActive(), numRowsAffected(), and QSqlDriver::hasFeature().
Example: sql/overview/navigating/main.cpp.
QVariant QSqlQuery::value ( int i ) const [virtual] π
returns the value of the i-th field in the query (zero based).
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. don't do it, bestie, u will not know which column is which and u will cry. π
an invalid QVariant is returned if field i does not exist, if the query is inactive, or if the query is positioned on an invalid record.
See also prev(), next(), first(), last(), seek(), isActive(), and isValid().
Examples:
β¨ SEE ALSO β¨
ok bestie you wanna keep going down the rabbit hole? here's where to go next π
π COPYRIGHT π
Copyright 1992-2007 Trolltech ASA, http://www.trolltech.com. π
the full legal tea is in the license file that ships with the distribution β go read that if you want the complete license statement, because that's where the whole thing lives. periodt.
π AUTHOR π
Generated automatically from the source code. no human author, just β¨the machineβ¨ doing its thing. iykyk. π
π¦ BUGS π¦
found a bug in Qt? okay queen, report it the way they describe over at http://doc.trolltech.com/bughowto.html. good bug reports help them help you. thank youuu π«Ά (genuinely, they mean it)
the definitive Qt documentation is in HTML format, and it lives at $QTDIR/doc/html β you can read it with Qt Assistant or honestly just any web browser, slay. this man page? it's a convenience thing for the people who prefer man pages, lowkey, although this format is not officially supported by Trolltech. so like. keep that in mind bestie π
if you find errors in this manual page, report them to qt-bugs@trolltech.com. and please, please include:
- the name of the manual page:
qsqlquery.3qt - the Qt version:
3.3.8
that's it, that's the whole vibe check. do that and you're a main character π
okay that's the whole page bestie, we made it to the end π this was Trolltech AS, dated 2 February 2007, for QSqlQuery(3qt) β go forth and query responsibly, no cap π β¨π
π¦ where this page comes from
- fedora 43: qt3-devel-docs 3.3.8b-102.fc43 Β· QPL-1.0 OR GPL-2.0-only OR GPL-3.0-only
- fedora 44: qt3-devel-docs 3.3.8b-103.fc44 Β· QPL-1.0 OR GPL-2.0-only OR GPL-3.0-only
- Copyright 1992-2007 Trolltech ASA. All rights reserved. See the
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms