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  ·  Modules  ·  Fonctions  · 

QSqlDriver Class Reference
[QtSql module]

The QSqlDriver class is an abstract base class for accessing specific SQL databases. More...

#include <QSqlDriver>

Inherits QObject.

Public Types

  • enum DriverFeature { Transactions, QuerySize, BLOB, Unicode, ..., BatchOperations }
  • enum IdentifierType { FieldName, TableName }
  • enum StatementType { WhereStatement, SelectStatement, UpdateStatement, InsertStatement, DeleteStatement }

Public Functions

  • QSqlDriver ( QObject * parent = 0 )
  • virtual bool beginTransaction ()
  • virtual void close () = 0
  • virtual bool commitTransaction ()
  • virtual QSqlResult * createResult () const = 0
  • virtual QString escapeIdentifier ( const QString & identifier, IdentifierType type ) const
  • virtual QString formatValue ( const QSqlField & field, bool trimStrings = false ) const
  • virtual QVariant handle () const
  • virtual bool hasFeature ( DriverFeature feature ) const = 0
  • virtual bool isOpen () const
  • bool isOpenError () const
  • QSqlError lastError () const
  • virtual bool open ( const QString & db, const QString & user = QString(), const QString & password = QString(), const QString & host = QString(), int port = -1, const QString & options = QString() ) = 0
  • virtual QSqlIndex primaryIndex ( const QString & tableName ) const
  • virtual QSqlRecord record ( const QString & tableName ) const
  • virtual bool rollbackTransaction ()
  • virtual QString sqlStatement ( StatementType type, const QString & tableName, const QSqlRecord & rec, bool preparedStatement ) const
  • virtual QStringList tables ( QSql::TableType tableType ) const
  • 28 public functions inherited from QObject

Protected Functions

  • 7 protected functions inherited from QObject

Additional Inherited Members

  • 1 property inherited from QObject
  • 1 public slot inherited from QObject
  • 1 signal inherited from QObject
  • 4 static public members inherited from QObject

Detailed Description

The QSqlDriver class is an abstract base class for accessing specific SQL databases.

This class should not be used directly. Use QSqlDatabase instead.

If you want to create your own SQL drivers, you can subclass this class and reimplement its pure virtual functions and those virtual functions that you need. See How to Write Your Own Database Driver for more information.

See also QSqlDatabase and QSqlResult.


Member Type Documentation

enum QSqlDriver::DriverFeature

This enum contains a list of features a driver might support. Use hasFeature() to query whether a feature is supported or not.

ConstantValueDescription
QSqlDriver::Transactions0Whether the driver supports SQL transactions.
QSqlDriver::QuerySize1Whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSqlQuery::size() will return -1.
QSqlDriver::BLOB2Whether the driver supports Binary Large Object fields.
QSqlDriver::Unicode3Whether the driver supports Unicode strings if the database server does.
QSqlDriver::PreparedQueries4Whether the driver supports prepared query execution.
QSqlDriver::NamedPlaceholders5Whether the driver supports the use of named placeholders.
QSqlDriver::PositionalPlaceholders6Whether the driver supports the use of positional placeholders.
QSqlDriver::LastInsertId7Whether the driver supports returning the Id of the last touched row.
QSqlDriver::BatchOperations8Whether the driver supports batched operations, see QSqlResult::execBatch()

More information about supported features can be found in the Qt SQL driver documentation.

See also hasFeature().

enum QSqlDriver::IdentifierType

This enum contains a list of SQL identifier types.

ConstantValueDescription
QSqlDriver::FieldName0A SQL field name
QSqlDriver::TableName1A SQL table name

enum QSqlDriver::StatementType

This enum contains a list of SQL statement (or clause) types the driver can create.

ConstantValueDescription
QSqlDriver::WhereStatement0An SQL WHERE statement (e.g., WHERE f = 5).
QSqlDriver::SelectStatement1An SQL SELECT statement (e.g., SELECT f FROM t).
QSqlDriver::UpdateStatement2An SQL UPDATE statement (e.g., UPDATE TABLE t set f = 1).
QSqlDriver::InsertStatement3An SQL INSERT statement (e.g., INSERT INTO t (f) values (1)).
QSqlDriver::DeleteStatement4An SQL DELETE statement (e.g., DELETE FROM t).

See also sqlStatement().


Member Function Documentation

QSqlDriver::QSqlDriver ( QObject * parent = 0 )

Constructs a new driver with the given parent.

QSqlDriver::~QSqlDriver ()

Destroys the object and frees any allocated resources.

bool QSqlDriver::beginTransaction ()   [virtual]

This function is called to begin a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also commitTransaction() and rollbackTransaction().

void QSqlDriver::close ()   [pure virtual]

Derived classes must reimplement this pure virtual function in order to close the database connection. Return true on success, false on failure.

See also open() and setOpen().

bool QSqlDriver::commitTransaction ()   [virtual]

This function is called to commit a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also beginTransaction() and rollbackTransaction().

QSqlResult * QSqlDriver::createResult () const   [pure virtual]

Creates an empty SQL result on the database. Derived classes must reimplement this function and return a QSqlResult object appropriate for their database to the caller.

QString QSqlDriver::escapeIdentifier ( const QString & identifier, IdentifierType type ) const   [virtual]

Returns the identifier escaped according to the database rules. identifier can either be a table name or field name, dependent on type.

The default implementation does nothing.

QString QSqlDriver::formatValue ( const QSqlField & field, bool trimStrings = false ) const   [virtual]

This is an overloaded member function, provided for convenience.

Returns a string representation of the field value for the database. This is used, for example, when constructing INSERT and UPDATE statements.

The default implementation returns the value formatted as a string according to the following rules:

  • If field is character data, the value is returned enclosed in single quotation marks, which is appropriate for many SQL databases. Any embedded single-quote characters are escaped (replaced with two single-quote characters). If trimStrings is true (the default is false), all trailing whitespace is trimmed from the field.
  • If field is date/time data, the value is formatted in ISO format and enclosed in single quotation marks. If the date/time data is invalid, "NULL" is returned.
  • If field is bytearray data, and the driver can edit binary fields, the value is formatted as a hexadecimal string.
  • For any other field type, toString() is called on its value and the result of this is returned.

See also QVariant::toString().

QVariant QSqlDriver::handle () const   [virtual]

Returns the low-level database handle wrapped in a QVariant or an invalid variant if there is no handle.

Warning: Use this with uttermost care and only if you know what you're doing.

Warning: The handle returned here can become a stale pointer if the connection is modified (for example, if you close the connection).

Warning: The handle can be NULL if the connection is not open yet.

The handle returned here is database-dependent, you should query the type name of the variant before accessing it.

This example retrieves the handle for a connection to sqlite:

    QSqlDatabase db = ...;
    QVariant v = db.driver()->handle();
    if (v.isValid() && v.typeName() == "sqlite3*") {
        // v.data() returns a pointer to the handle
        sqlite3 *handle = *static_cast<sqlite3 **>(v.data());
        if (handle != 0) { // check that it is not NULL
            ...
        }
    }

This snippet returns the handle for PostgreSQL or MySQL:

    if (v.typeName() == "PGconn*") {
        PGconn *handle = *static_cast<PGconn **>(v.data());
        if (handle != 0) ...
    }

    if (v.typeName() == "MYSQL*") {
        MYSQL *handle = *static_cast<MYSQL **>(v.data());
        if (handle != 0) ...
    }

See also QSqlResult::handle().

bool QSqlDriver::hasFeature ( DriverFeature feature ) const   [pure virtual]

Returns true if the driver supports feature feature; otherwise returns false.

Note that some databases need to be open() before this can be determined.

See also DriverFeature.

bool QSqlDriver::isOpen () const   [virtual]

Returns true if the database connection is open; otherwise returns false.

bool QSqlDriver::isOpenError () const

Returns true if the there was an error opening the database connection; otherwise returns false.

QSqlError QSqlDriver::lastError () const

Returns a QSqlError object which contains information about the last error that occurred on the database.

See also setLastError().

bool QSqlDriver::open ( const QString & db, const QString & user = QString(), const QString & password = QString(), const QString & host = QString(), int port = -1, const QString & options = QString() )   [pure virtual]

Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options.

The function must return true on success and false on failure.

See also setOpen().

QSqlIndex QSqlDriver::primaryIndex ( const QString & tableName ) const   [virtual]

Returns the primary index for table tableName. Returns an empty QSqlIndex if the table doesn't have a primary index. The default implementation returns an empty index.

QSqlRecord QSqlDriver::record ( const QString & tableName ) const   [virtual]

Returns a QSqlRecord populated with the names of the fields in table tableName. If no such table exists, an empty record is returned. The default implementation returns an empty record.

bool QSqlDriver::rollbackTransaction ()   [virtual]

This function is called to rollback a transaction. If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also beginTransaction() and commitTransaction().

void QSqlDriver::setLastError ( const QSqlError & error )   [virtual protected]

This function is used to set the value of the last error, error, that occurred on the database.

See also lastError().

void QSqlDriver::setOpen ( bool open )   [virtual protected]

This function sets the open state of the database to open. Derived classes can use this function to report the status of open().

See also open() and setOpenError().

void QSqlDriver::setOpenError ( bool error )   [virtual protected]

This function sets the open error state of the database to error. Derived classes can use this function to report the status of open(). Note that if error is true the open state of the database is set to closed (i.e., isOpen() returns false).

See also isOpenError(), open(), and setOpen().

QString QSqlDriver::sqlStatement ( StatementType type, const QString & tableName, const QSqlRecord & rec, bool preparedStatement ) const   [virtual]

Returns a SQL statement of type type for the table tableName with the values from rec. If preparedStatement is true, the string will contain placeholders instead of values.

This method can be used to manipulate tables without having to worry about database-dependend SQL dialects. For non-prepared statements, the values will be properly escaped.

QStringList QSqlDriver::tables ( QSql::TableType tableType ) const   [virtual]

Returns a list of the names of the tables in the database. The default implementation returns an empty list.

The tableType argument describes what types of tables should be returned. Due to binary compatibility, the string contains the value of the enum QSql::TableTypes as text. An empty string should be treated as QSql::Tables for backward compatibility.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 9
Page suivante

Le Qt Quarterly au hasard

Logo

Implémenter un mutex en lecture et en écriture

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. 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 4.1
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