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

30 篇文章 0 订阅
5 篇文章 0 订阅

参考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;
    }
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值