当前位置: 首页>>代码示例>>C++>>正文


C++ QSqlError函数代码示例

本文整理汇总了C++中QSqlError函数的典型用法代码示例。如果您正苦于以下问题:C++ QSqlError函数的具体用法?C++ QSqlError怎么用?C++ QSqlError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了QSqlError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: QSqlError

QSqlError SQLconnector::initDb()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(  QDir::currentPath() + "/Data.sqlite" );

    if (!db.open())
        return db.lastError();

    QStringList tables = db.tables();
    if (tables.contains("Article", Qt::CaseInsensitive)
        && tables.contains("Magazine", Qt::CaseInsensitive)
        && tables.contains("LienTheme", Qt::CaseInsensitive)){
        db.close();
        return QSqlError();
    }

    QSqlQuery q;


    if (!q.exec(QLatin1String("create table Article(id integer primary key, name varchar, description varchar,page integer, magazine integer)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table Magazine(id integer primary key, name varchar, numero integer)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table Theme(id integer primary key, name varchar, dependance integer)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table LienTheme(idArticle integer NOT NULL, idTheme integer NOT NULL, PRIMARY KEY ( idArticle, idTheme))")))
        return q.lastError();

    db.close();
    return QSqlError();
}
开发者ID:0CT3T,项目名称:QTMagazine,代码行数:31,代码来源:sqlconnector.cpp

示例2: filter

/*!
    Returns the SQL \c SELECT statement used internally to populate
    the model. The statement includes the filter and the \c{ORDER BY}
    clause.

    \sa filter(), orderByClause()
*/
QString QSqlTableModel::selectStatement() const
{
    Q_D(const QSqlTableModel);
    QString query;
    if (d->tableName.isEmpty()) {
        d->error = QSqlError(QLatin1String("No table name given"), QString(),
                             QSqlError::StatementError);
        return query;
    }
    if (d->rec.isEmpty()) {
        d->error = QSqlError(QLatin1String("Unable to find table ") + d->tableName, QString(),
                             QSqlError::StatementError);
        return query;
    }

    query = d->db.driver()->sqlStatement(QSqlDriver::SelectStatement,
                                         d->tableName,
                                         d->rec,
                                         false);
    if (query.isEmpty()) {
        d->error = QSqlError(QLatin1String("Unable to select fields from table ") + d->tableName,
                             QString(), QSqlError::StatementError);
        return query;
    }
    if (!d->filter.isEmpty())
        query.append(QLatin1String(" WHERE ")).append(d->filter);
    QString orderBy(orderByClause());
    if (!orderBy.isEmpty())
        query.append(QLatin1Char(' ')).append(orderBy);

    return query;
}
开发者ID:Blizzard,项目名称:qt4,代码行数:39,代码来源:qsqltablemodel.cpp

示例3: filter

/*!
    Returns the SQL \c SELECT statement used internally to populate
    the model. The statement includes the filter and the \c{ORDER BY}
    clause.

    \sa filter(), orderByClause()
*/
QString QSqlTableModel::selectStatement() const
{
    Q_D(const QSqlTableModel);
    if (d->tableName.isEmpty()) {
        d->error = QSqlError(QLatin1String("No table name given"), QString(),
                             QSqlError::StatementError);
        return QString();
    }
    if (d->rec.isEmpty()) {
        d->error = QSqlError(QLatin1String("Unable to find table ") + d->tableName, QString(),
                             QSqlError::StatementError);
        return QString();
    }

    const QString stmt = d->db.driver()->sqlStatement(QSqlDriver::SelectStatement,
                                                      d->tableName,
                                                      d->rec,
                                                      false);
    if (stmt.isEmpty()) {
        d->error = QSqlError(QLatin1String("Unable to select fields from table ") + d->tableName,
                             QString(), QSqlError::StatementError);
        return stmt;
    }
    return Sql::concat(Sql::concat(stmt, Sql::where(d->filter)), orderByClause());
}
开发者ID:OniLink,项目名称:Qt5-Rehost,代码行数:32,代码来源:qsqltablemodel.cpp

示例4: QSqlError

bool AbstractDocument::isValidDocumentFromProvod()
{
    if (lastError().isValid())
        return false;

    if (_isProvod) {
        _error = QSqlError("transactDocument",tr("Документ уже проведен! ")
                           ,QSqlError::UnknownError,100);
        return false;
    }

    QSqlQuery sql;
    sql.exec(QString("SELECT COUNT(*) FROM document_detail WHERE dd_doc = %1")
             .arg(_id));

    if (!sql.next()) {
        _error = sql.lastError();
        return false;
    }

    if (sql.value(0).toInt() == 0) {
        _error = QSqlError("transactDocument",
                           tr("Нет позиций для проводки! "),
                           QSqlError::UnknownError,100);
        return false;
    }

    return true;
}
开发者ID:wulff007,项目名称:FastStorage,代码行数:29,代码来源:documenttypes.cpp

示例5: syncToSqlRecord

bool TSqlObject::remove()
{
    syncToSqlRecord();
    QString del = TActionContext::currentDatabase().driver()->sqlStatement(QSqlDriver::DeleteStatement, tableName(), *static_cast<QSqlRecord *>(this), false);
    
    if (del.isEmpty()) {
        sqlError = QSqlError(QLatin1String("Unable to delete row"),
                             QString(), QSqlError::StatementError);
        return false;
    }

    del.append(" WHERE ");
    int revIndex = metaObject()->indexOfProperty(REVISION_PROPERTY_NAME);
    if (revIndex >= 0) {
        bool ok;
        int revsion = property(REVISION_PROPERTY_NAME).toInt(&ok);
        if (!ok || revsion <= 0) {
            sqlError = QSqlError(QLatin1String("Unable to convert the 'revision' property to an int"),
                                 QString(), QSqlError::UnknownError);
            tError("Unable to convert the 'revsion' property to an int, %s", qPrintable(objectName()));
            return false;
        }

        del.append(TSqlQuery::escapeIdentifier(REVISION_PROPERTY_NAME));
        del.append("=").append(TSqlQuery::formatValue(revsion));
        del.append(" AND ");
    }

    const char *pkName = metaObject()->property(metaObject()->propertyOffset() + primaryKeyIndex()).name();
    if (primaryKeyIndex() < 0 || !pkName) {
        QString msg = QString("Not found the primary key for table ") + tableName();
        sqlError = QSqlError(msg, QString(), QSqlError::StatementError);
        tError("%s", qPrintable(msg));
        return false;
    }
    del.append(TSqlQuery::escapeIdentifier(pkName));
    del.append("=").append(TSqlQuery::formatValue(property(pkName)));

    tSystemDebug("SQL statement: %s", qPrintable(del));
    QSqlQuery query(TActionContext::currentDatabase());
    bool res = query.exec(del);
    sqlError = query.lastError();
    if (!res) {
        tSystemError("SQL delete error: %s", qPrintable(sqlError.text()));
        return false;
    }
    
    // Optimistic lock check
    if (query.numRowsAffected() != 1) {
        if (revIndex >= 0) {
            QString msg = QString("Row was updated or deleted from table ") + tableName() + QLatin1String(" by another transaction");
            sqlError = QSqlError(msg, QString(), QSqlError::UnknownError);
            throw SqlException(msg, __FILE__, __LINE__);
        }
        tWarn("Row was deleted by another transaction, %s", qPrintable(tableName()));
    }

    clear();
    return true;
}
开发者ID:pivaldi,项目名称:TreeFrog,代码行数:60,代码来源:tsqlobject.cpp

示例6: isForwardOnly

/*!
    Resets the model and sets the data provider to be the given \a
    query. Note that the query must be active and must not be
    isForwardOnly().

    lastError() can be used to retrieve verbose information if there
    was an error setting the query.

    \sa query(), QSqlQuery::isActive(), QSqlQuery::setForwardOnly(), lastError()
*/
void QSqlQueryModel::setQuery(const QSqlQuery &query)
{
    Q_D(QSqlQueryModel);
    QSqlRecord newRec = query.record();
    bool columnsChanged = (newRec != d->rec);
    bool hasQuerySize = query.driver()->hasFeature(QSqlDriver::QuerySize);
    bool hasNewData = (newRec != QSqlRecord()) || !query.lastError().isValid();

    if (d->colOffsets.size() != newRec.count() || columnsChanged)
        d->initColOffsets(newRec.count());

    bool mustClearModel = d->bottom.isValid();
    if (mustClearModel) {
        d->atEnd = true;
        beginRemoveRows(QModelIndex(), 0, qMax(d->bottom.row(), 0));
        d->bottom = QModelIndex();
    }

    d->error = QSqlError();
    d->query = query;
    d->rec = newRec;

    if (mustClearModel)
        endRemoveRows();

    d->atEnd = false;

    if (columnsChanged && hasNewData)
        reset();

    if (!query.isActive() || query.isForwardOnly()) {
        d->atEnd = true;
        d->bottom = QModelIndex();
        if (query.isForwardOnly())
            d->error = QSqlError(QLatin1String("Forward-only queries "
                                               "cannot be used in a data model"),
                                 QString(), QSqlError::ConnectionError);
        else
            d->error = query.lastError();
        return;
    }
    QModelIndex newBottom;
    if (hasQuerySize && d->query.size() > 0) {
        newBottom = createIndex(d->query.size() - 1, d->rec.count() - 1);
        beginInsertRows(QModelIndex(), 0, qMax(0, newBottom.row()));
        d->bottom = createIndex(d->query.size() - 1, columnsChanged ? 0 : d->rec.count() - 1);
        d->atEnd = true;
        endInsertRows();
    } else {
        newBottom = createIndex(-1, d->rec.count() - 1);
    }
    d->bottom = newBottom;

    queryChange();

    // fetchMore does the rowsInserted stuff for incremental models
    fetchMore();
}
开发者ID:Akheon23,项目名称:chromecast-mirrored-source.vendor,代码行数:68,代码来源:qsqlquerymodel.cpp

示例7: update

QSqlError user_manager::update(user_ptr p)
{
   if (! p) { return QSqlError("cannot update user : invalid user (null pointer)", "", QSqlError::UnknownError); }
   if (p->id == 0) { return QSqlError("cannot update user : 'id' is required", "", QSqlError::UnknownError); }
   if (p->first_name.trimmed().isEmpty()) { return QSqlError("cannot update user : 'first_name' is required", "", QSqlError::UnknownError); }
   if (p->last_name.trimmed().isEmpty()) { return QSqlError("cannot update user : 'last_name' is required", "", QSqlError::UnknownError); }
   if (! qx::dao::exist(p)) { return QSqlError("cannot update user : user doesn't exist in database", "", QSqlError::UnknownError); }
   return qx::dao::update(p);
}
开发者ID:adamsheep,项目名称:QxOrm,代码行数:9,代码来源:user_manager.cpp

示例8: network

bool DataLayer::createnettable()
{
    QSqlQuery query;
    query.exec("	CREATE TABLE network(selfId integer primary key, parentId integer, name varchar, type int)");
    qDebug() << selfdb.databaseName() << selfdb.tables();
    if(QSqlError().isValid())
    {
        qDebug() << QSqlError();
        return false;
    }
    return true;
}
开发者ID:topillar,项目名称:QtFramelessWindow,代码行数:12,代码来源:database.cpp

示例9: Collection

/** \fn DatabaseManager::insertDirToCollection(const QString& dir)
  * \brief Inserts the directory \var dir into the Collection table.
  */
QSqlError DatabaseManager::insertDirToCollection(const QString& dir) {
    QSqlQuery q;
    q.prepare("INSERT INTO Collection (directory) VALUES (?)");
    q.bindValue(0, dir);

    if (!q.exec()) {
        if(q.lastError().type()==1 && q.lastError().text()=="constraint failed Unable to fetch row")
            return QSqlError();
        throw(q.lastError()); // TODO handle this!
    }

    return QSqlError();
}
开发者ID:slopjong,项目名称:MediaSpy,代码行数:16,代码来源:databasemanager.cpp

示例10: assert

QSqlError DbConnection::connect(DbList &dblist)
{
    assert(!dbuuid.isNull());

    if (!QSqlDatabase::isDriverAvailable(dbparam.driver))
    {
	QSqlError e = QSqlError("Could not connect to database",
				QString("Database driver %1 is not available.").arg(dbparam.driver),
				QSqlError::ConnectionError);
	dblist.tablelist_seterror(*this, e);
	return e;
    }

    db = QSqlDatabase::addDatabase(dbparam.driver, dbuuid);
	
    db.setHostName(dbparam.hostname);
    if (dbparam.port > 0) db.setPort(dbparam.port);
    db.setDatabaseName(dbparam.database);
    db.setUserName(dbparam.username);

    if (dbparam.askpassword)
    {
	bool ok;
	QString passwd = QInputDialog::getText(NULL, "QtSqlView Password Prompt",
					       QString("Enter password for '%1':").arg(dbparam.label),
					       QLineEdit::Password, QString::null, &ok);

	if (!ok) {
	    QSqlError e = QSqlError("Could not connect to database",
				    "Password prompt failed.",
				    QSqlError::ConnectionError);
	    dblist.tablelist_seterror(*this, e);
	    return e;
	}
    }
    else {
	db.setPassword(dbparam.password);
    }
	
    if (!db.open()) {
	QSqlError e = db.lastError();
	db = QSqlDatabase();
	QSqlDatabase::removeDatabase(dbuuid);
	dblist.tablelist_seterror(*this, e);
	return e;
    }

    dblist.tablelist_load(*this);

    return QSqlError();
}
开发者ID:bingmann,项目名称:bingmann.github.io,代码行数:51,代码来源:WMain.cpp

示例11: connectionName

QSqlDatabase QrSqlDatabase::createDatabase(QSqlError &dbError)
{
    QString connectionName_ = connectionName();
    dbError = QSqlError();

    dbFileIsCreated = false;
    qDebug() << "create database:" << getDatabasePath () << "," << connectionName_;
    if (! QrFiler::fileExists (getDatabasePath ())) {
//        qDebug() << "database path is not exist:" << getDatabasePath ();
//        dbError = QSqlError("'database file is not exist!'", "", QSqlError::ConnectionError);
//        Q_ASSERT(false);
//        return QrSqlDatabase::null;
        dbFileIsCreated = true;
        qDebug() << "database file is not exist, ready to creating...";
    }

    const QrSqlDatabaseParams &params = getParams ();
    Q_ASSERT(!params.driverName.isEmpty () && !params.databaseName.isEmpty ());
    QSqlDatabase db = QSqlDatabase::addDatabase (params.driverName, connectionName_);
    db.setConnectOptions (params.connectOptions);
    db.setDatabaseName (getDatabasePath ());
    db.setUserName (params.username);
    db.setPassword (params.password);
    db.setHostName (params.hostname);
    if (-1 != params.port){
        db.setPort (params.port);
    }

    if (! db.open ()) {
        qDebug() << "fail to open database";
        QrSqlDatabaseError::displayLastError (db, "unable to open connection to database");
        dbError = db.lastError ();
        if (!dbError.isValid ()) {
            dbError = QSqlError("'unable to open connection to database'", "", QSqlError::UnknownError);
        }
        QSqlDatabase::removeDatabase (connectionName_);
        return QrSqlDatabase::null;
    }

    Qt::HANDLE curThreadIdHandle = QThread::currentThreadId ();
    listDbByThread.insert (curThreadIdHandle, connectionName_);

    QString curThreadId = QrStringCvter<Qt::HANDLE, QrIsPointer<Qt::HANDLE>::value>::toString (curThreadIdHandle);
    qDebug() << "create new database connection of " << params.databaseName
             << "in thread " << curThreadId << " with key " << connectionName_;

    return QSqlDatabase::database(connectionName_);
}
开发者ID:Qters,项目名称:QrOrm,代码行数:48,代码来源:qrsqldatabase.cpp

示例12: removeRow

/*!
    Deletes the given \a row from the currently active database table.

    This is a low-level method that operates directly on the database
    and should not be called directly. Use removeRow() or removeRows()
    to delete values. The model will decide depending on its edit strategy
    when to modify the database.

    Returns true if the row was deleted; otherwise returns false.

    \sa removeRow(), removeRows()
*/
bool QSqlTableModel::deleteRowFromTable(int row)
{
    Q_D(QSqlTableModel);
    emit beforeDelete(row);

    const QSqlRecord whereValues = d->strategy == OnManualSubmit ? d->cache[row].primaryValues : d->primaryValues(row);
    bool prepStatement = d->db.driver()->hasFeature(QSqlDriver::PreparedQueries);
    QString stmt = d->db.driver()->sqlStatement(QSqlDriver::DeleteStatement,
                                                d->tableName,
                                                QSqlRecord(),
                                                prepStatement);
    QString where = d->db.driver()->sqlStatement(QSqlDriver::WhereStatement,
                                                 d->tableName,
                                                 whereValues,
                                                 prepStatement);

    if (stmt.isEmpty() || where.isEmpty()) {
        d->error = QSqlError(QLatin1String("Unable to delete row"), QString(),
                             QSqlError::StatementError);
        return false;
    }
    stmt.append(QLatin1Char(' ')).append(where);

    return d->exec(stmt, prepStatement, QSqlRecord() /* no new values */, whereValues);
}
开发者ID:phen89,项目名称:rtqt,代码行数:37,代码来源:qsqltablemodel.cpp

示例13: qMakeError

static QSqlError qMakeError(sqlite3 *access, const QString &descr, QSqlError::ErrorType type,
                            int errorCode = -1)
{
    return QSqlError(descr,
                     QString::fromUtf16( (const ushort *) sqlite3_errmsg16(access) ),
                     type, errorCode);
}
开发者ID:Br1ndavoine,项目名称:QGIS,代码行数:7,代码来源:qsql_spatialite.cpp

示例14: QSqlQuery

QSqlError QrSqlHelper::call_query(QrSqlQuery &query, QSqlDatabase *database /* = nullptr */)
{
    QSqlError dbError;
    if (dbError.isValid()) {
        return dbError;
    }

    QSqlQuery qQuery = QSqlQuery(*database);
    qQuery.setForwardOnly(true);

    QTime timeQuery;
    timeQuery.start ();
    qQuery.prepare (query.query ());
    query.resolve(qQuery);

    if (! qQuery.exec ()) {
        qDebug() << "query exec fail, " << query.query ();
        return qQuery.lastError ();
    }
    query.resolveOutput(qQuery, true);

    int ms = timeQuery.elapsed ();
    //  set is print sql query statement or not
    if (QrSqlConfig::getInstance ()->getTraceSqlQuery ()) {
        qDebug() << "custom sql query "<< "(" <<ms << " ms) : " << query.query ()
                 << " by " << database;
    }

    return QSqlError();
}
开发者ID:Qters,项目名称:QrOrm,代码行数:30,代码来源:qrsqlhelper.cpp

示例15: qMakeError

static QSqlError qMakeError(sqlite3 *access, const QString &descr, QSqlError::ErrorType type,
                            int errorCode = -1)
{
    return QSqlError(descr,
                     stringFromUnicode(reinterpret_cast<const QChar *>(sqlite3_errmsg16(access))),
                     type, errorCode);
}
开发者ID:Helgion,项目名称:quiterss,代码行数:7,代码来源:sqlitedriver.cpp


注:本文中的QSqlError函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。