【问题标题】:C++ SQLite3 how to know if select return 0 rowsC ++ SQLite3如何知道选择是否返回0行
【发布时间】:2012-08-15 00:22:29
【问题描述】:

C++ SQLite3如何知道select是否返回0行

我有一个sqlite3的select语句,我怎么知道如果执行sql语句后,结果是0行,没有找到匹配等等。

如何修改我的代码,以便如果找到 0 行,它将不会执行将结果放入向量的部分。

我的代码如下:

sqlstatement = "SELECT * from abe_account where department="+quotesql(department)+" AND name="+quotesql(name)+";";


    std::vector< std::vector < std:: string > > result;
    for( int i = 0; i < 4; i++ )
    result.push_back(std::vector< std::string >());


    sqlite3_prepare( db, sqlstatement.c_str() , -1, &stmt2, NULL );//preparing the statement
    sqlite3_step( stmt2 );//executing the statement

    while( sqlite3_column_text( stmt2, 0 ) )
{
    for( int i = 0; i < 4; i++ )
    result[i].push_back( std::string( (char *)sqlite3_column_text( stmt2, i ) ) );
    sqlite3_step( stmt2 );
    counter ++;
}

【问题讨论】:

  • 只需检查sqlite3_step的返回码...和RTFM。
  • 我在寻找什么返回码?我知道 101 执行成功
  • 你指的是“SQLITE_EMPTY”
  • @baokychen:SQLITE_ROW表示有一行; SQLITE_DONE 表示查询完成,没有更多行了。这在documentation 中有描述。

标签: c++ sqlite


【解决方案1】:

sqlite3_step 在没有(更多)行要处理时返回SQLITE_DONE

int stat = sqlite3_step(stmt2);
if (stat == SQLITE_DONE) {
    // no rows to process
}

记得检查错误,例如:

if (stat != SQLITE_DONE && stat != SQLITE_ROW) {
    // there's probably a problem
}

您可以找到complete list of result codes in the manual

最后,使用 SQLite3 时应该使用“v2”接口。 From the manual:

建议所有新程序使用 sqlite3_prepare_v2() 和 sqlite3_prepare16_v2() 接口。保留两个较旧的接口是为了向后兼容,但不鼓励使用它们。

【讨论】:

  • 我只想检查 SQLite 是否找到任何行,如果没有行,则返回 boolean success=false else success=true
  • @baokychen:你看答案了吗?我写的第一句话正是你需要的。
  • 问题是当你做那个检查时,第一行是阶梯式的,你不能处理它。如果不通过搜索的第一行,如何检查是否有行?
【解决方案2】:

先做一个SQL Count,如果返回0就可以停止执行,不需要查询select语句。

【讨论】:

  • 我如何进行 SQL 计数并检查其返回值是否为 0
  • 查询的结果应该是一个 int 作为结果。该 int 将是计数。 if (result[0] > 0){ //继续}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2014-11-24
  • 2019-12-17
  • 2020-03-09
  • 1970-01-01
相关资源
最近更新 更多