Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

QSqlQuery Class Reference
[sql module]

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

#include <qsqlquery.h>

Inherited by QSqlCursor.

List of all member functions.

Public Members

Protected Members


Detailed Description

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

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:

These functions allow the programmer to move forward, backward or arbitrarily through the records returned by the query. 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. For the sake of efficiency there are no methods to access a field by name. (The QSqlCursor class provides a higher level interface for that generates SQL automatically and through which fields are accessed by name.)

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.

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.

See also QSqlDatabase.

QSqlQuery::QSqlQuery ( const QSqlQuery & other )

Constructs a copy of other.

QSqlQuery::~QSqlQuery () [virtual]

Destroys the object and frees any allocated resources.

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.

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

const QSqlDriver * QSqlQuery::driver () const

Returns the database driver associated with the query.

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.

See also isActive(), isValid(), next(), prev(), first(), last() and seek().

Examples: sql/overview/basicbrowsing/main.cpp, sql/overview/basicbrowsing2/main.cpp and sql/overview/basicdatamanip/main.cpp.

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.

Example: sql/overview/navigating/main.cpp.

bool QSqlQuery::isActive () const

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

Examples: sql/overview/basicbrowsing/main.cpp, sql/overview/basicbrowsing2/main.cpp, sql/overview/basicdatamanip/main.cpp, sql/overview/navigating/main.cpp and sql/overview/retrieve1/main.cpp.

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() and value().

bool QSqlQuery::isSelect () const

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

bool QSqlQuery::isValid () 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.

Example: sql/overview/navigating/main.cpp.

QSqlError QSqlQuery::lastError () const

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

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.

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.

See also at() and isValid().

Examples: sql/overview/basicbrowsing/main.cpp, sql/overview/basicbrowsing2/main.cpp, sql/overview/del/main.cpp, sql/overview/order1/main.cpp, sql/overview/retrieve1/main.cpp, sql/overview/subclass4/main.cpp and sql/overview/subclass5/main.cpp.

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, this value will be the same as size(). If the query is not active (isActive() returns FALSE), -1 is returned.

See also size() and QSqlDriver::hasFeature().

Examples: sql/overview/basicbrowsing2/main.cpp and sql/overview/basicdatamanip/main.cpp.

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

Assigns other to the 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.

See also at().

const QSqlResult * QSqlQuery::result () const

Returns the result associated with the query.

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.

Example: sql/overview/navigating/main.cpp.

int QSqlQuery::size () const

Returns the size of the result, (number of rows returned), or -1 if the size cannot be determined or 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() 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.

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: sql/overview/basicbrowsing/main.cpp, sql/overview/basicbrowsing2/main.cpp, sql/overview/retrieve1/main.cpp, sql/overview/subclass3/main.cpp, sql/overview/subclass4/main.cpp, sql/overview/subclass5/main.cpp and sql/overview/table4/main.cpp.


This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  2. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  3. Une nouvelle ère d'IHM 3D pour les automobiles, un concept proposé par Digia et implémenté avec Qt 3
  4. Qt Creator 2.5 est sorti en beta, l'EDI supporte maintenant plus de fonctionnalités de C++11 2
  5. Vingt sociétés montrent leurs décodeurs basés sur Qt au IPTV World Forum, en en exploitant diverses facettes (déclaratif, Web, widgets) 0
  6. PySide devient un add-on Qt et rejoint le Qt Project et le modèle d'open gouvernance 1
  7. Thread travailleur avec Qt en utilisant les signaux et les slots, un article de Christophe Dumez traduit par Thibaut Cuvelier 1
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 102
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 51
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 229
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
  7. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 101
Page suivante

Le Qt Labs au hasard

Logo

Chaînes et SIMD, la revanche (de Latin1)

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 3.0
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web