Eneboo - Documentación para desarrolladores
Métodos públicos | Métodos protegidos
Referencia de la Clase QSqlQuery

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

#include <qsqlquery.h>

Diagrama de herencias de QSqlQuery
QSqlCursor QSqlCursor FLSqlCursor QSqlSelectCursor QSqlSelectCursor FLSqlCursor QSqlSelectCursor QSqlSelectCursor AQSqlCursor AQSqlCursor

Lista de todos los miembros.

Métodos públicos

 QSqlQuery (QSqlResult *r)
 QSqlQuery (const QString &query=QString::null, QSqlDatabase *db=0)
Q_EXPLICIT QSqlQuery (QSqlDatabase *db)
 QSqlQuery (const QSqlQuery &other)
QSqlQueryoperator= (const QSqlQuery &other)
virtual ~QSqlQuery ()
bool isValid () const
bool isActive () const
bool isNull (int field) const
int at () const
QString lastQuery () const
int numRowsAffected () const
virtual QSqlError lastError () const
bool isSelect () const
int size () const
const QSqlDriverdriver () const
const QSqlResultresult () const
bool isForwardOnly () const
void setForwardOnly (bool forward)
virtual bool exec (const QString &query)
virtual QVariant value (int i) const
virtual 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) const
QVariant boundValue (int pos) const
QMap< QString, QVariantboundValues () const
QString executedQuery () const
 QSqlQuery (QSqlResult *r)
 QSqlQuery (const QString &query=QString::null, QSqlDatabase *db=0)
Q_EXPLICIT QSqlQuery (QSqlDatabase *db)
 QSqlQuery (const QSqlQuery &other)
QSqlQueryoperator= (const QSqlQuery &other)
virtual ~QSqlQuery ()
bool isValid () const
bool isActive () const
bool isNull (int field) const
int at () const
QString lastQuery () const
int numRowsAffected () const
virtual QSqlError lastError () const
bool isSelect () const
int size () const
const QSqlDriverdriver () const
const QSqlResultresult () const
bool isForwardOnly () const
void setForwardOnly (bool forward)
virtual bool exec (const QString &query)
virtual QVariant value (int i) const
virtual 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) const
QVariant boundValue (int pos) const
QMap< QString, QVariantboundValues () const
QString executedQuery () const

Métodos protegidos

virtual void beforeSeek ()
virtual void afterSeek ()
virtual void beforeSeek ()
virtual void afterSeek ()

Descripción detallada

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

sql

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, e.g. SELECT, INSERT, UPDATE and DELETE, and also DDL (data definition language) statements, e.g. {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 (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.

Navigating records is performed with the following functions:

next() prev() first() last() QSqlQuery::seek() seek(int)

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. using next() or using seek() with a positive offset, you can use setForwardOnly() and save a significant amount of memory overhead. 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.)

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

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 with QSqlDriver::hasFeature() using QSqlDriver::PreparedQueries as 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.
Ver también:
QSqlDatabase QSqlCursor QVariant

Documentación del constructor y destructor

QSqlQuery::QSqlQuery ( QSqlResult r)

Creates a QSqlQuery object which uses the QSqlResult r to communicate with a database.

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.

Ver también:
QSqlDatabase
QSqlQuery::QSqlQuery ( QSqlDatabase db)

Creates a QSqlQuery object using the database db. If db is 0, the application's default database is used.

Ver también:
QSqlDatabase
QSqlQuery::QSqlQuery ( const QSqlQuery other)

Constructs a copy of other.

QSqlQuery::~QSqlQuery ( ) [virtual]

Destroys the object and frees any allocated resources.

QSqlQuery::QSqlQuery ( QSqlResult r)
QSqlQuery::QSqlQuery ( const QString query = QString::null,
QSqlDatabase db = 0 
)
Q_EXPLICIT QSqlQuery::QSqlQuery ( QSqlDatabase db)
QSqlQuery::QSqlQuery ( const QSqlQuery other)
virtual QSqlQuery::~QSqlQuery ( ) [virtual]

Documentación de las funciones miembro

void QSqlQuery::addBindValue ( const QVariant val)

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. Binds the placeholder with type QSql::In.

void QSqlQuery::addBindValue ( const QVariant val,
QSql::ParameterType  type 
)
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.

Ver también:
bindValue(), prepare(), exec()
void QSqlQuery::addBindValue ( const QVariant val)
void QSqlQuery::afterSeek ( ) [protected, virtual]

Protected virtual function called after the internal record pointer is moved to a new record. The default implementation does nothing.

Reimplementado en FLSqlCursor, QSqlCursor y QSqlCursor.

virtual void QSqlQuery::afterSeek ( ) [protected, virtual]

Reimplementado en FLSqlCursor, QSqlCursor y QSqlCursor.

int QSqlQuery::at ( ) const
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.

Ver también:
prev() next() first() last() seek() isActive() isValid()
void QSqlQuery::beforeSeek ( ) [protected, virtual]

Protected virtual function called before the internal record pointer is moved to a new record. The default implementation does nothing.

virtual void QSqlQuery::beforeSeek ( ) [protected, virtual]
void QSqlQuery::bindValue ( int  pos,
const QVariant val,
QSql::ParameterType  type 
)
void QSqlQuery::bindValue ( const QString placeholder,
const QVariant val 
)

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. Binds the placeholder with type QSql::In.

void QSqlQuery::bindValue ( int  pos,
const QVariant val 
)

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. Binds the placeholder at position pos with type QSql::In.

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.

Ver también:
addBindValue(), prepare(), exec()
void QSqlQuery::bindValue ( int  pos,
const QVariant val,
QSql::ParameterType  type 
)

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. 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.

Ver también:
addBindValue(), prepare(), exec()
void QSqlQuery::bindValue ( const QString placeholder,
const QVariant val 
)
void QSqlQuery::bindValue ( int  pos,
const QVariant val 
)
void QSqlQuery::bindValue ( const QString placeholder,
const QVariant val,
QSql::ParameterType  type 
)
QVariant QSqlQuery::boundValue ( int  pos) const

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. Returns the value for the placeholder at position pos.

QVariant QSqlQuery::boundValue ( const QString placeholder) const
QVariant QSqlQuery::boundValue ( int  pos) const
QVariant QSqlQuery::boundValue ( const QString placeholder) const

Returns the value for the placeholder.

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

Returns a map of the bound values.

The bound values can be examined in the following way:

    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++ );
    ...
QMap<QString, QVariant> QSqlQuery::boundValues ( ) const
const QSqlDriver * QSqlQuery::driver ( ) const

Returns the database driver associated with the query.

const QSqlDriver* QSqlQuery::driver ( ) const
bool QSqlQuery::exec ( )

Esta es una función miembro sobrecargada que se suministra por conveniencia. Difiere de la anterior función solamente en los argumentos que acepta. Executes a previously prepared SQL query. Returns TRUE if the query executed successfully; otherwise returns FALSE.

Ver también:
prepare(), bindValue(), addBindValue()
bool QSqlQuery::exec ( const QString query) [virtual]

Executes the SQL in query. Returns TRUE and sets the query state to active if the query was successful; otherwise returns FALSE and sets the query state to inactive. 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, e.g. using next().

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

Ver también:
isActive() isValid() next() prev() first() last() seek()

Reimplementado en FLSqlCursor, QSqlCursor, QSqlSelectCursor, QSqlCursor y QSqlSelectCursor.

virtual bool QSqlQuery::exec ( const QString query) [virtual]
bool QSqlQuery::exec ( )
QString QSqlQuery::executedQuery ( ) const
QString QSqlQuery::executedQuery ( ) const

Returns the last query that was executed.

In most cases this function returns the same 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. Useful for debugging purposes.

Ver también:
lastQuery()
bool QSqlQuery::first ( ) [virtual]

Retrieves the first record in the result, if available, and positions the query on the retrieved record. Note that the result must be in an 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.

Ver también:
next() prev() last() seek() at() isActive() isValid()
virtual bool QSqlQuery::first ( ) [virtual]
bool QSqlQuery::isActive ( ) const
bool QSqlQuery::isActive ( ) const

Returns TRUE if the query is currently active; otherwise returns FALSE.

bool QSqlQuery::isForwardOnly ( ) const
bool QSqlQuery::isForwardOnly ( ) const

Returns TRUE if you can only scroll forward through a result set; otherwise returns FALSE.

Ver también:
setForwardOnly()
bool QSqlQuery::isNull ( int  field) const

Reimplementado en QSqlCursor y QSqlCursor.

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.

Ver también:
isActive() isValid() value()

Reimplementado en QSqlCursor y QSqlCursor.

bool QSqlQuery::isSelect ( ) const

Returns TRUE if the current query is a SELECT statement; otherwise returns FALSE.

bool QSqlQuery::isSelect ( ) const
bool QSqlQuery::isValid ( ) const
bool QSqlQuery::isValid ( void  ) const

Returns TRUE if the query is currently positioned on a valid record; otherwise returns FALSE.

bool QSqlQuery::last ( ) [virtual]

Retrieves the last record in the result, if available, and positions the query on the retrieved record. Note that the result must be in an 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.

Ver también:
next() prev() first() seek() at() isActive() isValid()
virtual bool QSqlQuery::last ( ) [virtual]
QSqlError QSqlQuery::lastError ( ) const [virtual]

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

Ver también:
QSqlError

Reimplementado en QSqlCursor y QSqlCursor.

virtual QSqlError QSqlQuery::lastError ( ) const [virtual]

Reimplementado en QSqlCursor y QSqlCursor.

QString QSqlQuery::lastQuery ( ) const
QString QSqlQuery::lastQuery ( ) const

Returns the text of the current query being used, or QString::null if there is no current query text.

Ver también:
executedQuery()
virtual bool QSqlQuery::next ( ) [virtual]
bool QSqlQuery::next ( ) [virtual]

Retrieves the next record in the result, if available, and positions the query on the retrieved record. Note that the result must be in an 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.

Ver también:
prev() first() last() seek() at() isActive() isValid()
int QSqlQuery::numRowsAffected ( ) const
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; see size() instead. If the query is not active (isActive() returns FALSE), -1 is returned.

Ver también:
size() QSqlDriver::hasFeature()
QSqlQuery& QSqlQuery::operator= ( const QSqlQuery other)
QSqlQuery & QSqlQuery::operator= ( const QSqlQuery other)

Assigns other to the query.

bool QSqlQuery::prepare ( const QString query)

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

Ver también:
exec(), bindValue(), addBindValue()
bool QSqlQuery::prepare ( const QString query)
bool QSqlQuery::prev ( ) [virtual]

Retrieves the previous record in the result, if available, and positions the query on the retrieved record. Note that the result must be in an 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.

Ver también:
next() first() last() seek() at() isActive() isValid()
virtual bool QSqlQuery::prev ( ) [virtual]
const QSqlResult* QSqlQuery::result ( ) const
const QSqlResult * QSqlQuery::result ( ) const

Returns the result associated with the query.

virtual bool QSqlQuery::seek ( int  i,
bool  relative = FALSE 
) [virtual]
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 and isSelect() must return TRUE before calling this function.

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

If i 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 i. If the record at position i 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 i is negative, there is no change, and FALSE is returned. If the result is currently located after the last record, and i is positive, there is no change, and FALSE is returned. If the result is currently located somewhere in the middle, and the relative offset i 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 i records ahead of the current record (or i records behind the current record if i is negative). If the record at offset i could not be retrieved, the result is positioned after the last record if i >= 0, (or before the first record if i is negative), and FALSE is returned. If the record is successfully retrieved, TRUE is returned.

Ver también:
next() prev() first() last() at() isActive() isValid()
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.

Forward only mode is off by default.

Forward only mode cannot be used with data aware widgets like QDataTable, since they must to be able to scroll backward as well as forward.

Ver también:
isForwardOnly(), next(), seek()
void QSqlQuery::setForwardOnly ( bool  forward)
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().

Ver también:
isActive() numRowsAffected() QSqlDriver::hasFeature()
int QSqlQuery::size ( ) const
virtual QVariant QSqlQuery::value ( int  i) const [virtual]

Reimplementado en QSqlCursor y QSqlCursor.

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.

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.

Ver también:
prev() next() first() last() seek() isActive() isValid()

Reimplementado en QSqlCursor y QSqlCursor.


La documentación para esta clase fue generada a partir de los siguientes ficheros:
 Todo Clases Namespaces Archivos Funciones Variables 'typedefs' Enumeraciones Valores de enumeraciones Propiedades Amigas 'defines'