Exec query что это
Перейти к содержимому

Exec query что это

  • автор:

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:

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:

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 .

For an overview of the recommended types for use with Qt-supported Databases, please refer to this table.

You can navigate within the dataset 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 available 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.

If you navigate within a result set, and use next() and seek() only for browsing forward, 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 SELECT s. The following example inserts a record into a table using INSERT :

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:

Here’s an example of positional binding:

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:

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

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

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(). When using transactions you must start the transaction before you create your query.

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.

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Query vs Exec vs Prepare in Go

alok sinha

Go comes with a database/sql library to talk to any relational database. In a bid to abstract some of the low level complexities in connecting to the db and managing the connection pool, the exposed APIs seem to do a bit more than you actually expect them to do. This eventually leads to some confusion around how to use these APIs.

Hence, I’ve tried to analyze the behavior of the major APIs that one must be aware of before using them.

I did my experiments with my go application running on a virtual box (ubuntu) and a mysql server on my host machine.

Query tried: insert into items (name, price, description) values (‘brownie’,240,’sizzling’)

Query

We should always use db.Query whenever we want to do a select and we should never ignore the returned rows of Query but iterate over it (else we’ll leak the db connection!)

Doing Query(query) will not use a prepared statement (see the wireshark capture below)

  • Notice that only 1 TCP request was sent from client to server(minus login)
  • Connection will be released automatically to the pool when the returned rows are iterated, or we can call rows.Close() explicitly when we are done.
  • Usage — db.Query(“insert into items (name, price, description) values(‘brownie’, 240, ‘sizzling’)”)

Doing Query(queryTemplate, params) will use a prepared statement under the covers.

  • Notice that 3 TCP requests were sent from client to server(minus login)
  • Connection will be released automatically to the pool when the returned rows are iterated, or we can call rows.Close() explicitly when we are done.
  • Usage — db.Query(“insert into items (name, price, description) values(. )”, “brownie”, 240, “sizzling”)

Exec

We should always use db.Exec whenever we want to do an insert or update or delete.

Doing Exec(query) will not use a prepared statement, so lesser TCP calls to the SQL server

  • Notice that only 1 TCP request was sent from client to server(minus login)
  • Releases the connection automatically to the pool.
  • Usage — db.Exec(“insert into items (name, price, description) values(‘brownie’, 240, ‘sizzling’)”)

Doing Exec(queryTemplate, params) will use prepared statement under the covers, so more number of TCP calls to the SQL server.

  • Notice that 3 TCP requests were sent from client to server(minus login)
  • Releases the connection automatically to the pool.
  • Usage — db.Exec(“insert into items (name, price, description) values(. )”, “brownie”, 240, “sizzling”)

Prepare

This should be used only when we want to prepare once at the start of the program and execute N number of times during the course of the program.

  • Notice that 2 TCP requests were sent from client to server(minus login).
  • We need to close the statement explicitly when we don’t need the prepared statement anymore. Else, we’ll fail to free up allocated resources both on the client as well as server!
  • Usage — stmt.Exec(“insert into items (name, price, description) values(. )”, “brownie”, 240, “sizzling”)

Conclusion

One of the major confusions we ran into, while using this sql package for the first time was, we didn’t really know that it was creating prepared statements underneath even when we did not not explicitly instruct to do so.

Hopefully the points above clarify, when are prepared statements invoked and how we can avoid them.

Работа с БД в чем разница exec и execute в PDO

exec выполняет запрос, текст которого задан непосредственно в вызове exec. При этом в exec можно задавать только запросы, НЕ возвращающие наборы значений — никаких SELECT, SHOW и т. п. Для запросов, возвращающих наборы, используется не exec, а query.

execute выполняет параметризированный запрос, ранее созданный вызовом prepare. При этом в вызове execute передаются только параметры этого запроса. В prepare можно задать любой SQL-запрос — разделения на типы, как в exec / query, в prepare нет.

Нормальные СУБД поддерживают параметризованные запросы — когда текст запроса один раз передаётся в СУБД, а дальше многократно вызывается с разными значениями параметров — при этом СУБД передаются только наборы параметров.

Кроме того, параметризованные запросы — единственный надёжный способ защиты от SQL-инъекций.

Выполнение SQL-запросов

Класс QSqlQuery предоставляет интерфейс для выполнения операторов SQL и навигации по набору результатов запроса.

В QSqlQueryModel и QSqlTableModel классы , описанные в следующем разделе обеспечивают интерфейс более высокого уровня для доступа к базам данных. Если вы не знакомы с SQL, вы можете сразу перейти к следующему разделу ( Использование классов модели SQL ).

Выполнение запроса

Чтобы выполнить оператор SQL, просто создайте объект QSqlQuery и вызовите QSqlQuery::exec () следующим образом:

Конструктор QSqlQuery принимает необязательный объект QSqlDatabase, который указывает, какое соединение с базой данных использовать. В приведенном выше примере мы не указываем какое-либо соединение, поэтому используется соединение по умолчанию.

При возникновении ошибки exec () возвращает false . Затем ошибка доступна как QSqlQuery::lastError ().

Навигация набора результатов

QSqlQuery предоставляет доступ к результирующему набору по одной записи за раз. После вызова exec () внутренний указатель QSqlQuery располагается на одну позицию before первая запись. Мы должны вызвать QSqlQuery::next () один раз, чтобы перейти к первой записи, а затем еще раз next (), чтобы получить доступ к другим записям, пока он не вернет false . Вот типичный цикл, который перебирает все записи по порядку:

Функция QSqlQuery::value () возвращает значение поля в текущей записи. Поля задаются как индексы с отсчетом от нуля. QSqlQuery::value () возвращает QVariant , тип, который может содержать различные типы данных C++ и ядра Qt, такие как int , QString и QByteArray . Различные типы баз данных автоматически отображаются в ближайший эквивалент Qt. Во фрагменте кода мы вызываем QVariant::toString () и QVariant::toInt () для преобразования вариантов в QString и int .

Для обзора рекомендуемых типов для использования с базами данных, поддерживаемыми Qt, обратитесь к этой таблице .

Вы можете перемещаться по набору данных, используя QSqlQuery::next (), QSqlQuery::previous (), QSqlQuery::first (), QSqlQuery::last () и QSqlQuery::seek (). Текущий индекс строки возвращается функцией QSqlQuery::at (), а общее количество строк в результирующем наборе доступно как QSqlQuery::size () для баз данных, которые его поддерживают.

Чтобы определить, поддерживает ли драйвер базы данных данную функцию, используйте QSqlDriver::hasFeature (). В следующем примере мы вызываем QSqlQuery::size (), чтобы определить размер набора результатов базовой базы данных, поддерживающей эту функцию; в противном случае мы переходим к последней записи и используем позицию запроса, чтобы сообщить нам, сколько записей имеется.

Если вы перемещаетесь внутри набора результатов и используете next() и seek() только для просмотра вперед, вы можете вызвать QSqlQuery::setForwardOnly (true) перед вызовом exec(). Это простая оптимизация, которая значительно ускорит выполнение запроса при работе с большими наборами результатов.

Вставка,обновление и удаление записей

QSqlQuery может выполнять произвольные операторы SQL, а не только SELECT . В следующем примере запись в таблицу вставляется с помощью INSERT :

Если вы хотите вставить много записей одновременно,часто более эффективно отделить запрос от вставляемых фактических значений.Это можно сделать с помощью плейсхолдеров.Qt поддерживает два синтаксиса плейсхолдеров:именованная привязка и позиционная привязка.Вот пример именованной привязки:

Вот пример позиционной привязки:

Оба синтаксиса работают со всеми драйверами баз данных, предоставляемыми Qt. Если база данных изначально поддерживает синтаксис, Qt просто перенаправляет запрос в СУБД; в противном случае Qt имитирует синтаксис заполнителя путем предварительной обработки запроса. Фактический запрос, который в конечном итоге выполняется СУБД, доступен как QSqlQuery::executedQuery ().

При вставке нескольких записей достаточно один раз вызвать QSqlQuery::prepare (). Затем вы вызываете bindValue () или addBindValue (), а затем exec () столько раз, сколько необходимо.

Кроме производительности,одним из преимуществ плейсхолдеров является то,что вы можете легко указывать произвольные значения,не беспокоясь об экранировании специальных символов.

Обновление записи аналогично вставке ее в таблицу:

Вы также можете использовать именованную или позиционную привязку,чтобы связать параметры с фактическими значениями.

Наконец, вот пример оператора DELETE :

Transactions

Если базовое ядро ​​базы данных поддерживает транзакции, QSqlDriver::hasFeature ( QSqlDriver::Transactions ) вернет значение true. Вы можете использовать QSqlDatabase::transaction (), чтобы инициировать транзакцию, за которой следуют команды SQL, которые вы хотите выполнить в контексте транзакции, а затем либо QSqlDatabase::commit (), либо QSqlDatabase::rollback (). При использовании транзакций вы должны начать транзакцию до создания запроса.

Операции могут быть использованы для обеспечения того,чтобы сложная операция была атомарной (например,поиск постороннего ключа и создание записи),или для обеспечения средства отмены сложного изменения в середине.

exec_query

Importance_1

  • Class methods (1)
  • Importance_0_smnew
  • Instance methods (83)
  • Importance_1_smadd_limit! (
  • Importance_1_smadd_limit_offset! (
  • Importance_1_smadd_lock! (
  • Importance_1_smadd_transaction_record
  • Importance_0_smarel_from_relation
  • Importance_1_smbegin_db_transaction
  • Importance_1_smbegin_isolated_db_transaction
  • Importance_0_smbegin_transaction (
  • Importance_0_smbinds_from_relation (
  • Importance_0_smbuild_fixture_sql
  • Importance_0_smbuild_fixture_statements (>= v6.0.0)
  • Importance_0_smbuild_truncate_statement (>= v6.1.3.1)
  • Importance_0_smbuild_truncate_statements (>= v6.0.0)
  • Importance_1_smcacheable_query
  • Importance_0_smcase_sensitive_equality_ope. (
  • Importance_0_smcombine_multi_statements
  • Importance_1_smcommit_db_transaction
  • Importance_0_smcommit_transaction (
  • Importance_1_smcommit_transaction_records (
  • Importance_1_smcreate
  • Importance_0_smcurrent_transaction (
  • Importance_0_smdefault_insert_value
  • Importance_0_smdefault_sequence_name
  • Importance_1_smdelete
  • Importance_1_smdelete_sql (
  • Importance_0_smempty_insert_statement (
  • Importance_0_smempty_insert_statement_value
  • Importance_1_smexec_delete
  • Importance_1_smexec_insert
  • Importance_0_smexec_insert_all (>= v6.1.3.1)
  • Importance_1_smexec_query
  • Importance_0_smexec_rollback_db_transaction
  • Importance_0_smexec_rollback_to_savepoint (
  • Importance_1_smexec_update
  • Importance_1_smexecute
  • Importance_0_smexecute_batch (>= v6.0.0)
  • Importance_0_smexplain (>= v6.1.3.1)
  • Importance_1_sminsert
  • Importance_1_sminsert_fixture
  • Importance_1_sminsert_fixtures
  • Importance_0_sminsert_fixtures_set
  • Importance_1_sminsert_sql (
  • Importance_1_smjoin_to_delete
  • Importance_1_smjoin_to_update
  • Importance_0_smlast_inserted_id
  • Importance_0_smlimited_update_conditions (
  • Importance_0_smmark_transaction_written_if. (>= v6.1.3.1)
  • Importance_1_smoutside_transaction? (
  • Importance_0_smquery
  • Importance_0_smquery_value
  • Importance_0_smquery_values
  • Importance_1_smreset_sequence!
  • Importance_0_smreset_transaction
  • Importance_1_smrollback_db_transaction
  • Importance_0_smrollback_to_savepoint
  • Importance_0_smrollback_transaction (
  • Importance_1_smrollback_transaction_records (
  • Importance_1_smsanitize_limit
  • Importance_1_smselect
  • Importance_1_smselect_all
  • Importance_1_smselect_one
  • Importance_0_smselect_prepared
  • Importance_1_smselect_rows
  • Importance_1_smselect_value
  • Importance_3_smselect_values
  • Importance_0_smsingle_value_from_rows
  • Importance_0_smsql_for_insert
  • Importance_1_smsubquery_for
  • Importance_1_smsupports_statement_cache?
  • Importance_1_smto_sql
  • Importance_0_smto_sql_and_binds
  • Importance_4_smtransaction
  • Importance_0_smtransaction_isolation_levels
  • Importance_0_smtransaction_open?
  • Importance_0_smtransaction_state
  • Importance_1_smtruncate
  • Importance_0_smtruncate_tables (>= v6.0.0)
  • Importance_1_smupdate
  • Importance_1_smupdate_sql (
  • Importance_0_smwithin_new_transaction (
  • Importance_0_smwith_multi_statements (>= v6.0.0)
  • Importance_1_smwith_yaml_fallback
  • Importance_1_smwrite_query? (>= v6.0.0)

= private
= protected

Executes sql statement in the context of this connection using binds as the bind substitutes. name is logged along with the executed sql statement.

SQL под Qt: Начало

Эта заметка вкратце познакомит вас с основами использования модулей Qt для работы с реляционными базами данных. Предполагается, что знание SQL у вас уже имеется, хотя и не является столь критичным для понимания представленных примеров.

Рассматриваются базовые операции, необходимые для начала работы:

  • Открытие базы данных;
  • Выполнение запросов;
  • Выборка записей.

Подключение модуля sql к Qt-проекту

Для того, чтобы встроенные в Qt возможности для работы с SQL заработали, необходимо добавить в pro -файл следующую инструкцию:

Однако учитывайте, что драйвера различных баз данных устанавливаются в виде плагинов и могут отсутствовать в вашем дистрибутиве Qt. Особенно актуальной это проблема является под Windows в связи с лицензионными ограничениями на распространение бинарных пакетов. О том, как собрать нужный плагин, мы поговорим в другой раз.

Подключение к базе данных QSQLITE

Для простоты воспользуемся драйвером QSQLITE (предназначен для работы с SQLite ), поскольку он предустановлен во всех известных мне дистрибутивах Qt. К тому же, вам не потребуется устанавливать отдельную систему управлениями базами данных.

Рассмотрим соответствующий код подключения:

Если все прошло нормально, то в результате работы этого кода у вас появится пустой файл test в рабочем каталоге приложения. Так же обратите внимание на следующие функции-члены класса QSqlDatabase , которые потребуются вам, когда вы решите воспользоваться внешним сервером баз данных:

  • isValid();
  • setHostName();
  • setPort();
  • setDatabaseName();
  • setUserName();
  • setPassword();

Выполнение запросов с помощью QSqlQuery

Создадим в открытой базе данных новую таблицу с помощью QSqlQuery :

Аналогичным образом с помощью функции-члена exec() можно выполнять любые запросы к базе данных. Однако имеется одна тонкость.

Вставка записей в базу данных

Если запрос использует внешние данные, то в целях безопасности не вставляйте их напрямую, а используйте комбинацию prepare() и bindValue() :

Выборка записей из базы данных

Теперь рассмотрим способ получения записей из базы данных:

Заключение

Подводя итоги приведу полный листинг рассмотренного примера (обратите внимание на его завершение, дополненное кодом удаления таблицы и закрытия соединения с базой данных):

Exec query что это

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 )

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

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.

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

Positional binding using named placeholders

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

Binding values using positional placeholders #2

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.

See also QSqlDatabase, QSqlCursor, QVariant, and Database Classes.

MEMBER FUNCTION DOCUMENTATION

QSqlQuery::QSqlQuery ( QSqlResult * r )

QSqlQuery::QSqlQuery ( const QString & query = QString::null, QSqlDatabase * db = 0 )

See also QSqlDatabase.

explicit QSqlQuery::QSqlQuery ( QSqlDatabase * db )

See also QSqlDatabase.

QSqlQuery::QSqlQuery ( const QSqlQuery & other )

QSqlQuery::

void QSqlQuery::addBindValue ( const QVariant & val, QSql::ParameterType type )

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

void QSqlQuery::addBindValue ( const QVariant & val )

Binds the placeholder with type QSql::In.

void QSqlQuery::afterSeek () [virtual protected]

int QSqlQuery::at () const

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

void QSqlQuery::beforeSeek () [virtual protected]

void QSqlQuery::bindValue ( const QString & placeholder, const QVariant & val, QSql::ParameterType type )

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

void QSqlQuery::bindValue ( const QString & placeholder, const QVariant & val )

Binds the placeholder with type QSql::In.

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

Binds the placeholder at position pos with type QSql::In.

void QSqlQuery::bindValue ( int pos, const QVariant & val, QSql::ParameterType type )

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

QVariant QSqlQuery::boundValue ( int pos ) const

Returns the value for the placeholder at position pos.

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

The bound values can be examined in the following way:

const QSqlDriver * QSqlQuery::driver () const

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

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

bool QSqlQuery::exec ()

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

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]

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

bool QSqlQuery::isActive () const

bool QSqlQuery::isForwardOnly () const

See also setForwardOnly().

bool QSqlQuery::isNull ( int field ) const

See also isActive(), isValid(), and value().

bool QSqlQuery::isSelect () const

bool QSqlQuery::isValid () const

bool QSqlQuery::last () [virtual]

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

QSqlError QSqlQuery::lastError () const

See also QSqlError.

QString QSqlQuery::lastQuery () const

See also executedQuery().

bool QSqlQuery::next () [virtual]

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

int QSqlQuery::numRowsAffected () const

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

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

bool QSqlQuery::prepare ( const QString & query )

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

bool QSqlQuery::prev () [virtual]

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

bool QSqlQuery::seek ( int i, bool relative = FALSE ) [virtual]

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

void QSqlQuery::setForwardOnly ( bool forward )

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

To determine the number of rows affected by a non-SELECT statement, use numRowsAffected().

See also isActive(), numRowsAffected(), and QSqlDriver::hasFeature().

QVariant QSqlQuery::value ( int i ) const [virtual]

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

COPYRIGHT

AUTHOR

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 [email protected]. Please include the name of the manual page (qsqlquery.3qt) and the Qt version (3.3.8).

Exec query что это

На этом шаге мы рассмотрим различные методы выполнения запросов .

Чтобы выполнить запрос к базе, сначала следует создать экземпляр класса QSqlQuery . Для этого используется один из следующих форматов вызова его конструктора:

Первый формат позволяет сразу задать SQL -код, который следует выполнить, и немедленно запустить его на исполнение. Необязательный параметр db задает соединение с базой данных, запрос к которой следует выполнить, — если он не указан, будет использоваться соединение по умолчанию.

Второй формат создает пустой запрос, не содержащий ни SQL -кода, ни каких-либо прочих параметров, но позволяющий указать соединение к нужной базе данных. Третий запрос создает копию запроса, переданного в параметре.


    ехес (<SQL- код >) — немедленно выполняет переданный в параметре SQL -код. Если последний был успешно выполнен, возвращает True и переводит запрос в активное состояние, в противном случае возвращает False . Пример:

Здесь мы проверяем, есть ли в базе данных таблица good , и, если таковой нет, создаем ее SQL -командой CREATE TABLE .

Замечание . Метод exec() следует использовать в тех случаях, если SQL -запрос не принимает параметров. В противном случае рекомендуется применять методы, рассмотренные далее.

Здесь мы добавляем в только что созданную таблицу good запись, используя команду INSERT ;

Метод возвращает True , если запрос был успешно выполнен, и False — в противном случае. Пример:

На следующем шаге мы рассмотрим обработку результатов выполнения запросов .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *