Qsqlquery get error

The QtSql module helps you provide seamless database integration to your PyQt applications. More...

The QtSql module helps you provide seamless database integration to your PyQt applications. More…

Types


Detailed Description

The QtSql module helps you provide seamless database integration to your
PyQt applications.

The SQL classes are divided into three layers:

Layer Description
Driver Layer This comprises the classes QSqlDriver, QSqlDriverCreatorBase, and QSqlResult. This layer provides the low-level bridge between the specific databases and the SQL API layer. See SQL Database Drivers for more information.
SQL API Layer These classes provide access to databases. Connections are made using the QSqlDatabase class. Database interaction is achieved by using the QSqlQuery class. In addition to QSqlDatabase and QSqlQuery, the SQL API layer is supported by QSqlError, QSqlField, QSqlIndex, and QSqlRecord.
User Interface Layer These classes link the data from a database to data-aware widgets. They include QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel. These classes are designed to work with Qt’s model/view framework.

To import the module use, for example, the following statement:

from PyQt4 import QtSql

This overview assumes that you have at least a basic knowledge of SQL. You should be able to understand simple SELECT, INSERT, UPDATE, and DELETE statements. Although the QSqlTableModel class provides an interface to database browsing and editing that does not require a knowledge of SQL, a basic understanding of SQL is highly recommended. A standard text covering SQL databases is An Introduction to Database Systems (7th Ed.) by C. J. Date, ISBN 0201385902.

Topics:

  • Connecting to Databases
  • Executing SQL Statements
    • Executing a Query
    • Navigating the Result Set
    • Inserting, Updating, and Deleting Records
    • Transactions
  • Using the SQL Model Classes
    • The SQL Query Model
    • The SQL Table Model
    • The SQL Relational Table Model
  • Presenting Data in a Table View

Connecting to Databases

Before you can use QSqlQuery or QSqlQueryModel to access a database, you must create at least one database connection.

Database connections are identified by arbitrary strings. QSqlDatabase also supports the concept of a default connection, which is used by the Qt SQL class if no other connection is specified. This mechanism is very convenient for applications that use only one database connection.

The following code establishes a connection to a MySQL database called flightdb on host bigblue:

        QSqlDatabase db = QSqlDatabase.addDatabase("QMYSQL");
        db.setHostName("bigblue");
        db.setDatabaseName("flightdb");
        db.setUserName("acarlson");
        db.setPassword("1uTbSbAs");
        bool ok = db.open();

The first argument to QSqlDatabase.addDatabase() is the name of the driver. See the addDatabase() documentation for a list of drivers. We call setHostName(), setDatabaseName(), setUserName(), and setPassword() to initialize the connection information.

Since no name was specified for the connection, the connection serves as the default connection. To specify a name, pass it as the second argument to QSqlDatabase.addDatabase(). For example:

        QSqlDatabase firstDB = QSqlDatabase.addDatabase("QMYSQL", "first");
        QSqlDatabase secondDB = QSqlDatabase.addDatabase("QMYSQL", "second");

Once the connection is initialized, we must call QSqlDatabase.open() to open the database and give us access to the data. If this call fails it will return false; error information can be obtained from QSqlDatabase.lastError().

Once a connection is established, we can call the static function QSqlDatabase.database() from anywhere to get a pointer to a database connection. If we call it without a parameter, it will return the default connection. If called with the identifier used for a connection, it will return a reference to the specified connection. For example:

        QSqlDatabase defaultDB = QSqlDatabase.database();
        QSqlDatabase firstDB = QSqlDatabase.database("first");
        QSqlDatabase secondDB = QSqlDatabase.database("second");

To remove a database connection, first close the database using QSqlDatabase.close(), then remove it using the static method QSqlDatabase.removeDatabase().

Executing SQL Statements

The QSqlQuery class provides an interface for executing SQL statements and navigating through the result set of a query.

The QSqlQueryModel and QSqlTableModel classes described in the next section provide a higher-level interface for accessing databases. If you are unfamiliar with SQL, you might want to skip directly to the next section (Using the SQL Model Classes).

Executing a Query

To execute an SQL statement, simply create a QSqlQuery object and call QSqlQuery.exec() like this:

        QSqlQuery query;
        query.exec("SELECT name, salary FROM employee WHERE salary > 50000");

The QSqlQuery constructor accepts an optional QSqlDatabase object that specifies which database connection to use. In the example above, we don’t specify any connection, so the default connection is used.

If an error occurs, exec() returns false. The error is then available as QSqlQuery.lastError().

Navigating the Result Set

QSqlQuery provides access to the result set one record at a time. After the call to exec(), QSqlQuery’s internal pointer is located one position before the first record. We must call QSqlQuery.next() once to advance to the first record, then next() again repeatedly to access the other records, until it returns false. Here’s a typical loop that iterates over all the records in order:

        while (query.next()) {
            QString name = query.value(0).toString();
            int salary = query.value(1).toInt();
            qDebug() << name << salary;
        }

The QSqlQuery.value() function returns the value of a field in the current record. Fields are specified as zero-based indexes. QSqlQuery.value() returns a QVariant, a type that can hold various C++ and core Qt data types such as int, QString, and QByteArray. The different database types are automatically mapped into the closest Qt equivalent. In the code snippet, we call QVariant.toString() and QVariant.toInt() to convert variants to QString and int.

You can iterate back and forth using QSqlQuery.next(), QSqlQuery.previous(), QSqlQuery.first(), QSqlQuery.last(), and QSqlQuery.seek(). The current row index is returned by QSqlQuery.at(), and the total number of rows in the result set is avaliable as QSqlQuery.size() for databases that support it.

To determine whether a database driver supports a given feature, use QSqlDriver.hasFeature(). In the following example, we call QSqlQuery.size() to determine the size of a result set of the underlying database supports that feature; otherwise, we navigate to the last record and use the query’s position to tell us how many records there are.

        QSqlQuery query;
        int numRows;
        query.exec("SELECT name, salary FROM employee WHERE salary > 50000");

        QSqlDatabase defaultDB = QSqlDatabase.database();
        if (defaultDB.driver()->hasFeature(QSqlDriver.QuerySize)) {
            numRows = query.size();
        } else {
            // this can be very slow
            query.last();
            numRows = query.at() + 1;
        }

If you iterate through a result set only using next() and seek() with positive values, you can call QSqlQuery.setForwardOnly(true) before calling exec(). This is an easy optimization that will speed up the query significantly when operating on large result sets.

Inserting, Updating, and Deleting Records

QSqlQuery can execute arbitrary SQL statements, not just SELECTs. The following example inserts a record into a table using INSERT:

        QSqlQuery query;
        query.exec("INSERT INTO employee (id, name, salary) "
                   "VALUES (1001, 'Thad Beaumont', 65000)");

If you want to insert many records at the same time, it is often more efficient to separate the query from the actual values being inserted. This can be done using placeholders. Qt supports two placeholder syntaxes: named binding and positional binding. Here’s an example of named binding:

        QSqlQuery query;
        query.prepare("INSERT INTO employee (id, name, salary) "
                      "VALUES (:id, :name, :salary)");
        query.bindValue(":id", 1001);
        query.bindValue(":name", "Thad Beaumont");
        query.bindValue(":salary", 65000);
        query.exec();

Here’s an example of positional binding:

        QSqlQuery query;
        query.prepare("INSERT INTO employee (id, name, salary) "
                      "VALUES (?, ?, ?)");
        query.addBindValue(1001);
        query.addBindValue("Thad Beaumont");
        query.addBindValue(65000);
        query.exec();

Both syntaxes work with all database drivers provided by Qt. If the database supports the syntax natively, Qt simply forwards the query to the DBMS; otherwise, Qt simulates the placeholder syntax by preprocessing the query. The actual query that ends up being executed by the DBMS is available as QSqlQuery.executedQuery().

When inserting multiple records, you only need to call QSqlQuery.prepare() once. Then you call bindValue() or addBindValue() followed by exec() as many times as necessary.

Besides performance, one advantage of placeholders is that you can easily specify arbitrary values without having to worry about escaping special characters.

Updating a record is similar to inserting it into a table:

        QSqlQuery query;
        query.exec("UPDATE employee SET salary = 70000 WHERE id = 1003");

You can also use named or positional binding to associate parameters to actual values.

Finally, here’s an example of a DELETE statement:

        QSqlQuery query;
        query.exec("DELETE FROM employee WHERE id = 1007");

Transactions

If the underlying database engine supports transactions, QSqlDriver.hasFeature(QSqlDriver.Transactions) will return true. You can use QSqlDatabase.transaction() to initiate a transaction, followed by the SQL commands you want to execute within the context of the transaction, and then either QSqlDatabase.commit() or QSqlDatabase.rollback().

Example:

        QSqlDatabase.database().transaction();
        QSqlQuery query;
        query.exec("SELECT id FROM employee WHERE name = 'Torild Halvorsen'");
        if (query.next()) {
            int employeeId = query.value(0).toInt();
            query.exec("INSERT INTO project (id, name, ownerid) "
                       "VALUES (201, 'Manhattan Project', "
                       + QString.number(employeeId) + ")");
        }
        QSqlDatabase.database().commit();

Transactions can be used to ensure that a complex operation is atomic (for example, looking up a foreign key and creating a record), or to provide a means of canceling a complex change in the middle.

Using the SQL Model Classes

In addition to QSqlQuery, Qt offers three higher-level classes for accessing databases. These classes are QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel.

These classes derive from QAbstractTableModel (which in turn inherits from QAbstractItemModel) and make it easy to present data from a database in an item view class such as QListView and QTableView. This is explained in detail in the Presenting Data in a Table View section.

Another advantage of using these classes is that it can make your code easier to adapt to other data sources. For example, if you use QSqlTableModel and later decide to use XML files to store data instead of a database, it is essentially just a matter of replacing one data model with another.

The SQL Query Model

QSqlQueryModel offers a read-only model based on an SQL query.

Example:

        QSqlQueryModel model;
        model.setQuery("SELECT * FROM employee");

        for (int i = 0; i < model.rowCount(); ++i) {
            int id = model.record(i).value("id").toInt();
            QString name = model.record(i).value("name").toString();
            qDebug() << id << name;
        }

After setting the query using QSqlQueryModel.setQuery(), you can use QSqlQueryModel.record(int) to access the individual records. You can also use QSqlQueryModel.data() and any of the other functions inherited from QAbstractItemModel.

There’s also a setQuery() overload that takes a QSqlQuery object and operates on its result set. This enables you to use any features of QSqlQuery to set up the query (e.g., prepared queries).

The SQL Table Model

QSqlTableModel offers a read-write model that works on a single SQL table at a time.

Example:

        QSqlTableModel model;
        model.setTable("employee");
        model.setFilter("salary > 50000");
        model.setSort(2, Qt.DescendingOrder);
        model.select();

        for (int i = 0; i < model.rowCount(); ++i) {
            QString name = model.record(i).value("name").toString();
            int salary = model.record(i).value("salary").toInt();
            qDebug() << name << salary;
        }

QSqlTableModel is a high-level alternative to QSqlQuery for navigating and modifying individual SQL tables. It typically results in less code and requires no knowledge of SQL syntax.

Use QSqlTableModel.record() to retrieve a row in the table, and QSqlTableModel.setRecord() to modify the row. For example, the following code will increase every employee’s salary by 10 per cent:

        for (int i = 0; i < model.rowCount(); ++i) {
            QSqlRecord record = model.record(i);
            double salary = record.value("salary").toInt();
            salary *= 1.1;
            record.setValue("salary", salary);
            model.setRecord(i, record);
        }
        model.submitAll();

You can also use QSqlTableModel.data() and QSqlTableModel.setData(), which are inherited from QAbstractItemModel, to access the data. For example, here’s how to update a record using setData():

        model.setData(model.index(row, column), 75000);
        model.submitAll();

Here’s how to insert a row and populate it:

        model.insertRows(row, 1);
        model.setData(model.index(row, 0), 1013);
        model.setData(model.index(row, 1), "Peter Gordon");
        model.setData(model.index(row, 2), 68500);
        model.submitAll();

Here’s how to delete five consecutive rows:

        model.removeRows(row, 5);
        model.submitAll();

The first argument to QSqlTableModel.removeRows() is the index of the first row to delete.

When you’re finished changing a record, you should always call QSqlTableModel.submitAll() to ensure that the changes are written to the database.

When and whether you actually need to call submitAll() depends on the table’s edit strategy. The default strategy is QSqlTableModel.OnRowChange, which specifies that pending changes are applied to the database when the user selects a different row. Other strategies are QSqlTableModel.OnManualSubmit (where all changes are cached in the model until you call submitAll()) and QSqlTableModel.OnFieldChange (where no changes are cached). These are mostly useful when QSqlTableModel is used with a view.

QSqlTableModel.OnFieldChange seems to deliver the promise that you never need to call submitAll() explicitly. There are two pitfalls, though:

  • Without any caching, performance may drop significantly.
  • If you modify a primary key, the record might slip through your fingers while you are trying to populate it.

The SQL Relational Table Model

QSqlRelationalTableModel extends QSqlTableModel to provide support for foreign keys. A foreign key is a 1-to-1 mapping between a field in one table and the primary key field of another table. For example, if a book table has a field called authorid that refers to the author table’s id field, we say that authorid is a foreign key.

The screenshot on the left shows a plain QSqlTableModel in a QTableView. Foreign keys (city and country) aren’t resolved to human-readable values. The screenshot on the right shows a QSqlRelationalTableModel, with foreign keys resolved into human-readable text strings.

The following code snippet shows how the QSqlRelationalTableModel was set up:

        model->setTable("employee");

        model->setRelation(2, QSqlRelation("city", "id", "name"));
        model->setRelation(3, QSqlRelation("country", "id", "name"));

See the QSqlRelationalTableModel documentation for details.

Presenting Data in a Table View

The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel classes can be used as a data source for Qt’s view classes such as QListView, QTableView, and QTreeView. In practice, QTableView is by far the most common choice, because an SQL result set is essentially a two-dimensional data structure.

A table view displaying a QSqlTableModel

The following example creates a view based on an SQL data model:

        QTableView *view = new QTableView;
        view->setModel(model);
        view->show();

If the model is a read-write model (e.g., QSqlTableModel), the view lets the user edit the fields. You can disable this by calling

        view->setEditTriggers(QAbstractItemView.NoEditTriggers);

You can use the same model as a data source for multiple views. If the user edits the model through one of the views, the other views will reflect the changes immediately. The Table Model example shows how it works.

View classes display a header at the top to label the columns. To change the header texts, call setHeaderData() on the model. The header’s labels default to the table’s field names. For example:

        model->setHeaderData(0, Qt.Horizontal, QObject.tr("ID"));
        model->setHeaderData(1, Qt.Horizontal, QObject.tr("Name"));
        model->setHeaderData(2, Qt.Horizontal, QObject.tr("City"));
        model->setHeaderData(3, Qt.Horizontal, QObject.tr("Country"));

QTableView also has a vertical header on the left with numbers identifying the rows. If you insert rows programmatically using QSqlTableModel.insertRows(), the new rows will be marked with an asterisk (*) until they are submitted using submitAll() or automatically when the user moves to another record (assuming the edit strategy is QSqlTableModel.OnRowChange).

Inserting a row in a model

Likewise, if you remove rows using removeRows(), the rows will be marked with an exclamation mark (!) until the change is submitted.

The items in the view are rendered using a delegate. The default delegate, QItemDelegate, handles the most common data types (int, QString, QImage, etc.). The delegate is also responsible for providing editor widgets (e.g., a combobox) when the user starts editing an item in the view. You can create your own delegates by subclassing QAbstractItemDelegate or QItemDelegate. See Model/View Programming for more information.

QSqlTableModel is optimized to operate on a single table at a time. If you need a read-write model that operates on an arbitrary result set, you can subclass QSqlQueryModel and reimplement flags() and setData() to make it read-write. The following two functions make fields 1 and 2 of a query model editable:

    Qt.ItemFlags EditableSqlModel.flags(
            const QModelIndex &index) const
    {
        Qt.ItemFlags flags = QSqlQueryModel.flags(index);
        if (index.column() == 1 || index.column() == 2)
            flags |= Qt.ItemIsEditable;
        return flags;
    }

    bool EditableSqlModel.setData(const QModelIndex &index, const QVariant &value, int /* role */)
    {
        if (index.column() < 1 || index.column() > 2)
            return false;

        QModelIndex primaryKeyIndex = QSqlQueryModel.index(index.row(), 0);
        int id = data(primaryKeyIndex).toInt();

        clear();

        bool ok;
        if (index.column() == 1) {
            ok = setFirstName(id, value.toString());
        } else {
            ok = setLastName(id, value.toString());
        }
        refresh();
        return ok;
    }

The setFirstName() helper function is defined as follows:

    bool EditableSqlModel.setFirstName(int personId, const QString &firstName)
    {
        QSqlQuery query;
        query.prepare("update person set firstname = ? where id = ?");
        query.addBindValue(firstName);
        query.addBindValue(personId);
        return query.exec();
    }

The setLastName() function is similar. See the Query Model example for the complete source code.

Subclassing a model makes it possible to customize it in many ways: You can provide tooltips for the items, change the background color, provide calculated values, provide different values for viewing and editing, handle null values specially, and more. See Model/View Programming as well as the QAbstractItemView reference documentation for details.

If all you need is to resolve a foreign key to a more human-friendly string, you can use QSqlRelationalTableModel. For best results, you should also use QSqlRelationalDelegate, a delegate that provides combobox editors for editing foreign keys.

Editing a foreign key in a relational table

The Relational Table Model example illustrates how to use QSqlRelationalTableModel in conjunction with QSqlRelationalDelegate to provide tables with foreign key support.


admsasha

Гость


   

    QSqlDatabase db =  QSqlDatabase::addDatabase(«QMYSQL»);
    db.setDatabaseName(«test»);
    db.setUserName(«mylogin»);
    db.setPassword(«mypassword»);
    db.setHostName(«127.0.0.1»);

Этот код работает замечательно.

   QSqlQuery query(QSqlDatabase::database(«test»));
   query.prepare(«SELECT table from user»);
   if(!query.exec()){
        qDebug() <<  query.lastError().text();
    }else{
         qDebug() << query.value(0);
    }

   

случайно ошибаюсь и пишу так

   QSqlQuery query(QSqlDatabase::database(«test»));
   query.prepare(«SELECT tble from user»);
   if(!query.exec()){
        qDebug() <<  query.lastError().text();
    }else{
        qDebug() << query.value(0);
    }

   

но query.lastError().text() выдает «». Почему нет текста ? Как правильно вывести текст ошибки ?


Записан
ecspertiza

Супер
******
Offline Offline

Сообщений: 1053

С уважением, мастер конфетного цеха!

Просмотр профиля


Если я правильно понимаю то prepare() немного для другого предназначен

попробуй так

  QSqlQuery query;
   if(!query.exec(«SELECT tble from user»)){
        qDebug() << «Error» << query.lastError();
    }else{
        qDebug() << query.value(0);
    }


Записан
admsasha

Гость


Если я правильно понимаю то prepare() немного для другого предназначен

попробуй так

  QSqlQuery query;
   if(!query.exec(«SELECT tble from user»)){
        qDebug() << «Error» << query.lastError();
    }else{
        qDebug() << query.value(0);
    }

Да, так показывает. Но мне нужно вставлять параметры в SQL, в случае prepare я делал это через bindValue, а тут как быть ?


Записан
ecspertiza

Супер
******
Offline Offline

Сообщений: 1053

С уважением, мастер конфетного цеха!

Просмотр профиля


Я просто думаю что это зависит от запросов, если ты делаешь просто Select то наверное не стоит пользоваться prepare()

А вот если с подстановкой параметров то можно и с prepare();

может prepare() если без параметров не отрабатывает или ещё что, точно сказать не могу.

Ты можешь формировать сначала строку запроса просто в QString а потом подставлять её в exec();

Ну и накройняк ты после выполнения exec() можешь посмотреть какой у тебя запрос в БД пошёл QSqlQuery::lastQuery();


Записан

Means of executing and manipulating SQL statements

Synopsis

#include <qsqlquery.h>

Inherited by QSqlCursor.

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 () const
bool isActive () const
bool isNull ( int field ) const
int at () const
QString lastQuery () const
int numRowsAffected () const
QSqlError lastError () const
bool isSelect () const
int size () const
const QSqlDriver * driver () const
const QSqlResult * result () 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, QVariant> boundValues () const
QString executedQuery () const

Protected Members

virtual void beforeSeek ()
virtual void afterSeek ()

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:

next()

prev()

first()

last()

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.

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

QSqlQuery::~QSqlQuery () [virtual]

Destroys the object and frees any allocated resources.

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.

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

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

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:

bool QSqlQuery::exec ()

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

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

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

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.

Examples:

bool QSqlQuery::isForwardOnly () const

Returns TRUE if you 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. 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.

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.

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]

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 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 for SELECT statements, the value is undefined; see size() instead. 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.

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.

See also exec(), bindValue(), and addBindValue().

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 next(), first(), last(), seek(), at(), isActive(), and isValid().

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.

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.

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.

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

See Also

http://doc.trolltech.com/qsqlquery.html http://www.trolltech.com/faq/tech.html

Copyright

Copyright 1992-2007 Trolltech ASA, http://www.trolltech.com.  See the license file included in the distribution for a complete license statement.

Bugs

If you find a bug in Qt, please report it as described in http://doc.trolltech.com/bughowto.html. Good bug reports help us to help you. Thank you.

The definitive Qt documentation is provided in HTML format; it is located at $QTDIR/doc/html and can be read using Qt Assistant or with a web browser. This man page is provided as a convenience for those users who prefer man pages, although this format is not officially supported by Trolltech.

If you find errors in this manual page, please report them to qt-bugs@trolltech.com. Please include the name of the manual page (qsqlquery.3qt) and the Qt version (3.3.8).

Referenced By

The man page QSqlQuery.3qt(3) is an alias of qsqlquery.3qt(3).

2 February 2007 Trolltech AS

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

#include <qsqlquery.h>

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, QVariant >  boundValues () 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 QSqlDriver *  driver () 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…
 
QSqlQuery &  operator= (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 QSqlResult *  result () 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…
 

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:

  • next()
  • previous()
  • first()
  • last()
  • seek()

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()) {

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:

query.prepare(«INSERT INTO person (id, forename, surname) «

«VALUES (:id, :forename, :surname)»);

query.bindValue(«:forename», «Bart»);

query.bindValue(«:surname», «Simpson»);

Positional binding using named placeholders:

query.prepare(«INSERT INTO person (id, forename, surname) «

«VALUES (:id, :forename, :surname)»);

Binding values using positional placeholders (version 1):

query.prepare(«INSERT INTO person (id, forename, surname) «

«VALUES (?, ?, ?)»);

Binding values using positional placeholders (version 2):

query.prepare(«INSERT INTO person (id, forename, surname) «

«VALUES (?, ?, ?)»);

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.

query.prepare(«CALL AsciiToInt(?, ?)»);

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.

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

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

Definition at line 236 of file qsqlquery.cpp.

237 {

239 }

const QSqlResult * result() const

Returns the result associated with the query.

◆ QSqlQuery() [2/4]

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 }

static void qInit(QSqlQuery *q, const QString &query, QSqlDatabase db)

static QSqlQueryPrivate * shared_null()

◆ QSqlQuery() [3/4]

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 {

301 }

The QString class provides a Unicode character string.

static void qInit(QSqlQuery *q, const QString &query, QSqlDatabase db)

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;

259 }

bool ref()

Atomically increments the value of this QAtomicInt.

◆ ~QSqlQuery()

QSqlQuery::~QSqlQuery ( )

Destroys the object and frees any allocated resources.

Definition at line 245 of file qsqlquery.cpp.

246 {

248  delete d;

249 }

bool deref()

Atomically decrements the value of this QAtomicInt.

◆ addBindValue()

void QSqlQuery::addBindValue ( const QVariant &  val,
QSql::ParamType  paramType = QSql::In 
)

◆ at()

int QSqlQuery::at ( ) const

◆ 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 {

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

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 {

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

static QByteArray paramType(const QByteArray &ptype, bool *out)

◆ boundValue() [1/2]

Returns the value for the placeholder.

See also
boundValues() bindValue() addBindValue()

Definition at line 1070 of file qsqlquery.cpp.

1071 {

1073 }

QVariant boundValue(const QString &placeholder) const

Returns the value bound by the given placeholder name in the current record (row).

◆ 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 {

1081 }

QVariant boundValue(const QString &placeholder) const

Returns the value bound by the given placeholder name in the current record (row).

◆ boundValues()

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:

for (int i = 0; i < list.size(); ++i)

See also
boundValue() bindValue() addBindValue()

Definition at line 1097 of file qsqlquery.cpp.

1098 {

1100 

1102  for (int i = 0; i < values.count(); ++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).

QFuture< void > map(Sequence &sequence, MapFunction function)

QVector< QVariant > & boundValues() const

Returns a vector of the result's bound values for the current record (row).

◆ 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 {

877 }

const QSqlDriver * driver() const

Returns the database driver associated with the query.

QSqlQuery(QSqlResult *r)

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

◆ driver()

◆ 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:

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

362  } else {

368  }

371  qWarning(«QSqlQuery::exec: database not open»);

372  return false;

373  }

375  qWarning(«QSqlQuery::exec: empty query»);

376  return false;

377  }

378 #ifdef QT_DEBUG_SQL

380 #endif

382 }

The QSqlError class provides SQL database error information.

const QSqlDriver * driver() const

Returns the database driver associated with the query.

QSqlQuery(QSqlResult *r)

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

virtual bool isOpen() const

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

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…

virtual void setLastError(const QSqlError &e)

This function is provided for derived classes to set the last error to error.

void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy)

bool isOpenError() const

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

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.

bool isEmpty() const

Returns true if the string has no characters; otherwise returns false.

Q_CORE_EXPORT void qWarning(const char *,…)

QByteArray toLocal8Bit() const Q_REQUIRED_RESULT

Returns the local 8-bit representation of the string as a QByteArray.

void setForwardOnly(bool forward)

Sets forward only mode to forward.

virtual bool reset(const QString &sqlquery)=0

Sets the result to use the SQL statement query for subsequent data retrieval.

const char * constData() const

Returns a pointer to the data stored in the byte array.

void clear()

Clears the entire result set and releases any associated resources.

virtual void setActive(bool a)

This function is provided for derived classes to set the internal active state to active…

bool isForwardOnly() const

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

virtual void setQuery(const QString &query)

Sets the current query for the result to query.

◆ exec() [2/2]

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 

949 

951 }

The QSqlError class provides SQL database error information.

virtual void setLastError(const QSqlError &e)

This function is provided for derived classes to set the last error to error.

virtual bool exec()

Executes the query, returning true if successful; otherwise returns false.

QSqlError lastError() const

Returns the last error associated with the result.

bool isValid() const

Returns true if an error is set, otherwise false.

◆ execBatch()

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;

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 {

1008 }

bool execBatch(bool arrayBind=false)

Executes a prepared query in batch mode if the driver supports it, otherwise emulates a batch executi…

◆ 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 {

1122 }

QString executedQuery() const

Returns the query that was actually executed.

◆ 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 {

1212  }

1213 }

The QSqlError class provides SQL database error information.

bool isActive() const

Returns true if the query is active.

virtual void setAt(int at)

This function is provided for derived classes to set the internal (zero-based) row position to index…

virtual void setLastError(const QSqlError &e)

This function is provided for derived classes to set the last error to error.

void detachFromResultSet()

virtual void setActive(bool a)

This function is provided for derived classes to set the internal active state to active…

◆ 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 {

681  return false;

683  qWarning(«QSqlQuery::seek: cannot seek backwards in a forward only query»);

684  return false;

685  }

686  bool b = false;

688  return b;

689 }

bool isActive() const

Returns true if the query is active.

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

Q_CORE_EXPORT void qWarning(const char *,…)

bool isForwardOnly() const

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

int at() const

Returns the current internal position of the query.

◆ 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 {

788 }

bool isActive() const

Returns true if the result has records to be retrieved; otherwise returns false.

◆ isForwardOnly()

bool QSqlQuery::isForwardOnly ( ) const

◆ 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 {

327  return true;

328 }

bool isActive() const

Returns true if the result has records to be retrieved; otherwise returns false.

bool isValid() const

Returns true if the result is positioned on a valid record (that is, the result is not positioned bef…

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 {

798 }

bool isSelect() const

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

◆ 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 {

767 }

bool isValid() const

Returns true if the result is positioned on a valid record (that is, the result is not positioned bef…

◆ 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 {

706  return false;

707  bool b = false;

709  return b;

710 }

bool isActive() const

Returns true if the query is active.

bool isSelect() const

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

virtual bool fetchLast()=0

Positions the result to the last record (last row) in the result.

◆ lastError()

◆ 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 {

1151 }

virtual QVariant lastInsertId() const

Returns the object ID of the most recent inserted row if the database supports it.

◆ 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 {

435 }

QString lastQuery() const

Returns the current SQL query text, or an empty string if there isn't one.

◆ 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 {

597  return false;

598  bool b = false;

599  switch (at()) {

602  return b;

604  return false;

605  default:

608  return false;

609  }

610  return true;

611  }

612 }

bool isActive() const

Returns true if the query is active.

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

virtual void setAt(int at)

This function is provided for derived classes to set the internal (zero-based) row position to index…

virtual bool fetchNext()

Positions the result to the next available record (row) in the result.

int at() const

Returns the current internal position of the query.

◆ 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 {

1252  return false;

1253 }

bool isActive() const

Returns true if the query is active.

◆ numericalPrecisionPolicy()

◆ 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 {

744  return -1;

745 }

bool isActive() const

Returns true if the query is active.

virtual int numRowsAffected()=0

Returns the number of rows affected by the last query executed, or -1 if it cannot be determined or i…

◆ operator=()

Assigns other to this object.

Definition at line 308 of file qsqlquery.cpp.

309 {

311  return *this;

312 }

void qAtomicAssign(T *&d, T *x)

This is a helper for the assignment operators of implicitly shared classes.

◆ 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:

query.prepare(«INSERT INTO person (id, forename, surname) «

«VALUES (:id, :forename, :surname)»);

query.bindValue(«:forename», «Bart»);

query.bindValue(«:surname», «Simpson»);

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

910  } else {

915  }

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  }

925  qWarning(«QSqlQuery::prepare: empty query»);

926  return false;

927  }

928 #ifdef QT_DEBUG_SQL

930 #endif

932 }

The QSqlError class provides SQL database error information.

const QSqlDriver * driver() const

Returns the database driver associated with the query.

QSqlQuery(QSqlResult *r)

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

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…

virtual void setLastError(const QSqlError &e)

This function is provided for derived classes to set the last error to error.

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.

bool isEmpty() const

Returns true if the string has no characters; otherwise returns false.

Q_CORE_EXPORT void qWarning(const char *,…)

QByteArray toLocal8Bit() const Q_REQUIRED_RESULT

Returns the local 8-bit representation of the string as a QByteArray.

void setForwardOnly(bool forward)

Sets forward only mode to forward.

const char * constData() const

Returns a pointer to the data stored in the byte array.

virtual void setActive(bool a)

This function is provided for derived classes to set the internal active state to active…

bool isForwardOnly() const

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

◆ 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 {

646  return false;

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;

658  return b;

659  default:

662  return false;

663  }

664  return true;

665  }

666 }

bool isActive() const

Returns true if the query is active.

bool isSelect() const

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

virtual void setAt(int at)

This function is provided for derived classes to set the internal (zero-based) row position to index…

Q_CORE_EXPORT void qWarning(const char *,…)

virtual bool fetchLast()=0

Positions the result to the last record (last row) in the result.

virtual bool fetchPrevious()

Positions the result to the previous record (row) in the result.

bool isForwardOnly() const

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

int at() const

Returns the current internal position of the query.

◆ record()

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»);

qDebug() << «Number of columns: « << rec.count();

int nameCol = rec.indexOf(«name»);

while (q.next())

qDebug() << q.value(nameCol).toString();

See also
value()

Definition at line 858 of file qsqlquery.cpp.

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

859 {

861 

863  for (int i = 0; i < rec.count(); ++i)

865  }

866  return rec;

867 }

The QSqlRecord class encapsulates a database record.

virtual QSqlRecord record() const

Returns the current record if the query is active; otherwise returns an empty QSqlRecord.

int count() const

Returns the number of fields in the record.

void setValue(int i, const QVariant &val)

Sets the value of the field at position index to val.

QVariant value(int i) const

Returns the value of field index in the current record.

bool isValid() const

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

◆ result()

◆ 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 {

505  return false;

506  int actualIdx;

507  if (!relative) {

510  return false;

511  }

512  actualIdx = index;

513  } else {

514  switch (at()) {

517  actualIdx = index;

518  else {

519  return false;

520  }

521  break;

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 

541  qWarning(«QSqlQuery::seek: cannot seek backwards in a forward only query»);

542  return false;

543  }

547  return false;

548  }

549  return true;

550  }

551  if (actualIdx == (at() — 1)) {

554  return false;

555  }

556  return true;

557  }

560  return false;

561  }

562  return true;

563 }

bool isActive() const

Returns true if the query is active.

bool isSelect() const

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

virtual void setAt(int at)

This function is provided for derived classes to set the internal (zero-based) row position to index…

virtual bool fetchNext()

Positions the result to the next available record (row) in the result.

Q_CORE_EXPORT void qWarning(const char *,…)

virtual bool fetchLast()=0

Positions the result to the last record (last row) in the result.

virtual bool fetchPrevious()

Positions the result to the previous record (row) in the result.

bool isForwardOnly() const

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

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.

◆ 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 {

838 }

virtual void setForwardOnly(bool forward)

Sets forward only mode to forward.

◆ setNumericalPrecisionPolicy()

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 {

1177 }

void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy)

◆ 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 {

728  return -1;

729 }

const QSqlDriver * driver() const

Returns the driver associated with the result.

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.

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 {

407  qWarning(«QSqlQuery::value: not positioned on a valid record»);

409 }

The QVariant class acts like a union for the most common Qt data types.

bool isActive() const

Returns true if the query is active.

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 *,…)

bool isValid() const

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

◆ d


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

  • /src/sql/kernel/qsqlquery.h
  • /src/sql/kernel/qsqlquery.cpp

Понравилась статья? Поделить с друзьями:
  • Pythonanywhere oserror write error
  • Qsoundeffect qaudio error decoding source
  • Python39 dll ошибка
  • Python35 dll ошибка
  • Qserialport timeout error