📄 qsqlquery.cpp
字号:
/*! Sets forward only mode to \a forward. If \a 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 \c setForwardMode() 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. \sa isForwardOnly(), next(), seek()*/void QSqlQuery::setForwardOnly(bool forward){ d->sqlResult->setForwardOnly(forward);}/*! 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 \c{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. \code QSqlQuery q("select * from employees"); QSqlRecord rec = q.record(); qDebug() << "Number of columns: " << rec.count(); int nameCol = rec.indexOf("name"); // index of the field "name" while (q.next()) qDebug() << q.value(nameCol).toString(); // output all names \endcode \sa value()*/QSqlRecord QSqlQuery::record() const{ QSqlRecord rec = d->sqlResult->record(); if (isValid()) { for (int i = 0; i < rec.count(); ++i) rec.setValue(i, value(i)); } return rec;}/*! Clears the result set and releases any resources held by the query. You should rarely if ever need to call this function.*/void QSqlQuery::clear(){ *this = QSqlQuery(driver()->createResult());}/*! Prepares the SQL query \a 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., \c{:surname}), and ODBC style (\c{?}) placeholders are supported; but they cannot be mixed in the same query. See the \l{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. \sa exec(), bindValue(), addBindValue()*/bool QSqlQuery::prepare(const QString& query){ if (d->ref != 1) { bool fo = isForwardOnly(); *this = QSqlQuery(driver()->createResult()); setForwardOnly(fo); d->sqlResult->setNumericalPrecisionPolicy(d->precisionPolicy); } else { d->sqlResult->setActive(false); d->sqlResult->setLastError(QSqlError()); d->sqlResult->setAt(QSql::BeforeFirstRow); d->sqlResult->setNumericalPrecisionPolicy(d->precisionPolicy); } if (!driver()) { qWarning("QSqlQuery::prepare: no driver"); return false; } if (!driver()->isOpen() || driver()->isOpenError()) { qWarning("QSqlQuery::prepare: database not open"); return false; } if (query.isEmpty()) { qWarning("QSqlQuery::prepare: empty query"); return false; }#ifdef QT_DEBUG_SQL qDebug("\n QSqlQuery::prepare: %s", query.toLocal8Bit().constData());#endif return d->sqlResult->savePrepare(query);}/*! \overload Executes a previously prepared SQL query. Returns true if the query executed successfully; otherwise returns false. \sa prepare() bindValue() addBindValue() boundValue() boundValues()*/bool QSqlQuery::exec(){ d->sqlResult->resetBindCount(); return d->sqlResult->exec();}/*! \enum QSqlQuery::BatchExecutionMode \value ValuesAsRows - Updates multiple rows. Treats every entry in a QVariantList as a value for updating the next row. \value ValuesAsColumns - Updates a single row. Treats every entry in a QVariantList as a single value of an array type.*//*! \since 4.2 Executes a previously prepared SQL query in a batch. 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: \code QSqlQuery q; q.prepare("insert into myTable values (?, ?)"); QVariantList ints; ints << 1 << 2 << 3 << 4; q.addBindValue(ints); QVariantList names; names << "Harald" << "Boris" << "Trond" << QVariant(QVariant::String); q.addBindValue(names); if (!q.execBatch()) qDebug() << q.lastError(); \endcode The example above inserts four new rows into \c myTable: \code 1 Harald 2 Boris 3 Trond 4 NULL \endcode To bind NULL values, a null QVariant of the relevant type has to be added to the bound QVariantList; for example, \c {QVariant(QVariant::String)} should be used if you are using strings. Note that every bound QVariantList must contain the same amount of variants. Note that the type of the QVariants in a list must not change. For example, you cannot mix integer and string variants within a QVariantList. The \a mode parameter indicates how the bound QVariantList will be interpreted. If \a mode is \c ValuesAsRows, every variant within the QVariantList will be interpreted as a value for a new row. \c 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 \c{TYPE myType IS TABLE OF VARCHAR(64) INDEX BY BINARY_INTEGER;} \sa prepare(), bindValue(), addBindValue()*/bool QSqlQuery::execBatch(BatchExecutionMode mode){ return d->sqlResult->execBatch(mode == ValuesAsColumns);}/*! Set the placeholder \a placeholder to be bound to value \a val in the prepared statement. Note that the placeholder mark (e.g \c{:}) must be included when specifying the placeholder name. If \a paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call. To bind a NULL value, use a null QVariant; for example, use \c {QVariant(QVariant::String)} if you are binding a string. \sa addBindValue(), prepare(), exec(), boundValue() boundValues()*/void QSqlQuery::bindValue(const QString& placeholder, const QVariant& val, QSql::ParamType paramType){ d->sqlResult->bindValue(placeholder, val, paramType);}/*! \overload Set the placeholder in position \a pos to be bound to value \a val in the prepared statement. Field numbering starts at 0. If \a paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call.*/void QSqlQuery::bindValue(int pos, const QVariant& val, QSql::ParamType paramType){ d->sqlResult->bindValue(pos, val, paramType);}/*! Adds the value \a 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 \a paramType is QSql::Out or QSql::InOut, the placeholder will be overwritten with data from the database after the exec() call. To bind a NULL value, use a null QVariant; for example, use \c {QVariant(QVariant::String)} if you are binding a string. \sa bindValue(), prepare(), exec(), boundValue() boundValues()*/void QSqlQuery::addBindValue(const QVariant& val, QSql::ParamType paramType){ d->sqlResult->addBindValue(val, paramType);}/*! Returns the value for the \a placeholder. \sa boundValues() bindValue() addBindValue()*/QVariant QSqlQuery::boundValue(const QString& placeholder) const{ return d->sqlResult->boundValue(placeholder);}/*! \overload Returns the value for the placeholder at position \a pos.*/QVariant QSqlQuery::boundValue(int pos) const{ return d->sqlResult->boundValue(pos);}/*! Returns a map of the bound values. With named binding, the bound values can be examined in the following ways: \quotefromfile snippets/sqldatabase/sqldatabase.cpp \skipto examine with named binding \skipto QMapIterator \printuntil } With positional binding, the code becomes: \skipto examine with positional binding \skipto QList \printuntil endl; \sa boundValue() bindValue() addBindValue()*/QMap<QString,QVariant> QSqlQuery::boundValues() const{ QMap<QString,QVariant> map; const QVector<QVariant> values(d->sqlResult->boundValues()); for (int i = 0; i < values.count(); ++i) map[d->sqlResult->boundValueName(i)] = values.at(i); return map;}/*! 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. \sa lastQuery()*/QString QSqlQuery::executedQuery() const{ return d->sqlResult->executedQuery();}/*! \fn bool QSqlQuery::prev() Use previous() instead.*//*! 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. Note that for Oracle databases the row's ROWID will be returned, while for MySQL databases the row's auto-increment field will be returned. \sa QSqlDriver::hasFeature()*/QVariant QSqlQuery::lastInsertId() const{ return d->sqlResult->lastInsertId();}/*! Instruct the database driver to return numerical values with a precision specified by \a precisionPolicy. The Oracle driver, for example, retrieves numerical values as strings by default to prevent the loss of precision. If the 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 \l{exec()}{exec(QString)} or prepare() in order to activate the policy. \sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy()*/void QSqlQuery::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy){ d->precisionPolicy = precisionPolicy;}/*! Returns the current precision policy. \sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy()*/QSql::NumericalPrecisionPolicy QSqlQuery::numericalPrecisionPolicy() const{ return d->precisionPolicy;}/*! \since 4.3.2 \preliminary Instruct the database driver that no more data will be fetched from this query until it is re-executed. 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. This function is new in Qt 4.3.2 and requires that QT_44_API_QSQLQUERY_FINISH is defined when compiling your application. It is expected to become part of the public API in Qt 4.4. \sa prepare() exec() isActive()*/void QSqlQuery::finish(){ if (isActive()) { d->sqlResult->setLastError(QSqlError()); d->sqlResult->setAt(QSql::BeforeFirstRow); d->sqlResult->detachFromResultSet(); d->sqlResult->setActive(false); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -