Qt中SQL的使用之判断某个字段是否已存在库中

参考Qt Documentation中的QSqlQuery Class部分
思路如下:
首先用SELECT语句进行查询,通过bool QSqlQuery::exec(const QString &query)函数执行查询,但是要注意不能用bool QSqlQuery::exec(const QString &query)的返回值来判断是否存在,因为其返回值只能用来判断语句是否正常执行,正如文档中所说的:

Returns true and sets the query state to active if the query was successful; otherwise returns false.

要想判断字段是否已存在,就要检查SELECT查询的结果。注意到bool QSqlQuery::exec(const QString &query)函数执行后:

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

因此可以用bool QSqlQuery::next()来检查查询的结果,文档中是这么说明该函数的返回的:

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.

所以,假如字段已存在,那么就存在相应的记录,返回值为true;假如字段不存在,那么无法获得相应的记录,返回值为false。这就可以用于判断。

示例代码如下:

bool isExisted(const QString &isbn)
{
    QSqlQuery query;
    query.exec(QString("SELECT * from book WHERE isbn = '%1'").arg(isbn));
    if(!query.next()){
        qDebug() << "The book doesn't exist." << endl;
        return 0;
    }
    else{
        qDebug() << "The book exists." << endl;
        return 1;
    }
}

如果程序中使用QSqlTableModel *model来操作数据库,并且model已经关联到一个QTableView来显示,那么可能会使用下述代码来判断,这样做有一个问题,就是会使得QTableView中实时显示SELECT的查询结果,比如若是字段不存在,那么QTableView中就会什么都不显示了。
更新:以下代码只能判断SELECT语句是否执行了,并不能返回判断字段是否存在的bool,但是同时会刷新QTableView,使QTableView显示SELECT语句的结果。

//The method below will update the tableview
bool isExisted2(const QString &isbn)
{
    model->setFilter(QString("isbn= '%1'").arg(isbn));
    if (!model->select()){
        qDebug() << "The book doesn't exist." << endl;
        return 0;
    }
    else{
        qDebug() << "The book exists." << endl;
        return 1;
    }
}

猜你喜欢

转载自blog.csdn.net/u013213111/article/details/87957791