1

目前我正在使用以下代码,但是如何在执行语句后检索计数以查看表是否包含数据?

NSString *sql2 = @"SELECT COUNT( * ) FROM myTable";
sqlite3_stmt *stmt2 = [Cn OpenSQL:[sql2 UTF8String]];

if (stmt2 != nil) 
{
    if(sqlite3_step(stmt2)){
    NSLog(@"success")
    }
    else NSLog(@"err2: %@",sql2);
}
4

2 回答 2

2
NSString *sql2 = SELECT COUNT(*) FROM `myTable`;

如果结果为 0,则表示表为空。

if (sqlite3_open([self.dataBasePath UTF8String], &articlesDB) == SQLITE_OK)
    {
        const char* sqlStatement = "SELECT COUNT(*) FROM MYTABLE";
        sqlite3_stmt *statement;

        if( sqlite3_prepare_v2(articlesDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
        {
            //Loop through all the returned rows (should be just one)
            while( sqlite3_step(statement) == SQLITE_ROW )
            {
                NSInteger count = sqlite3_column_int(statement, 0);
                NSLog(@"Rowcount is %d",count);
            }
        }
        else
        {
            NSLog( @"Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(articlesDB) );
        }

        // Finalize and close database.
        sqlite3_finalize(statement);
        sqlite3_close(articlesDB);
    }
于 2012-05-21T12:07:25.763 回答
2
NSInteger count = sqlite3_column_int(statement, 0); 
// value of count will give you the answer

如果count == 0,则没有数据。

如果count > 0,则表中有一个可用的元组。

于 2012-05-21T14:24:53.093 回答