sqlite 判断某条数据是否存在

1、判断某条数据是否存在

bool DataBaseManager::WriteConfigure(QString configureName, QString configureVal)
{
    QString sql = QString("select 1 from Configure where configureName = '%1' limit 1;").arg(configureName);
    QSqlQuery query(m_DBZHdb);
    if (query.exec(sql))
    {
        int nIndex = query.record().indexOf("1");
        query.next();
        int nCount = query.value(nIndex).toInt();
        
        if (nCount == 1) {
            //存在则更新
            sql = QString("update Configure set configureVal = '%1' where configureName = '%2'").arg(configureVal).arg(configureName);
        }
        else
        {
            //不存在,则插入
            sql = QString("insert into Configure(configureName,configureVal) Values('%1','%2')").arg(configureName).arg(configureVal);
        }
        bool b = query.exec(sql);
        if (b) {
            ReadConfigure();//重新加载
        }
        return b;
    }
    else
    {
        return false;
    }

}

 2022年10月18日更新:又发现一个判断记录是否存在的方法

bool OperateSqlite::IsRecordExist1(const QString& tbName, const QString& field, const QString& value)
{
    QString strQuery;

    strQuery = QString("SELECT * FROM %1 WHERE %2='%3';").arg(tbName).arg(field).arg(value);

    QSqlQuery query(strQuery, m_sqlDataBase);
    return query.next();
}

 

2、获取某条数据有多少条

int DataBaseManager::getTrackPointCount(const QString & taskName, const QString & personNo)
{
    QSqlQuery query(m_chatMsgdb);
    QString sql = QString("SELECT COUNT(id) FROM taskState_%1 WHERE targetId='%2';").arg(taskName).arg(personNo);

    if (query.exec(sql))
    {
        if (query.next())
        {
            int count = query.value(0).toInt();
            return count;
        }
    }
    return 0;
}

 

posted @ 2022-03-18 14:36  阳光下的小土豆  阅读(3467)  评论(0编辑  收藏  举报