计算 SQLite 数据库中的行数 [英] Count Number of Rows in a SQLite Database

查看:47
本文介绍了计算 SQLite 数据库中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码来计算我的 SQLite 数据库表中的行数,但它引发了异常.这是一种更简单的方法吗?

I'm trying the following code to count the number of rows in my SQLite database table, but it throws an exception. Is these a simpler way to do this?

- (void) countRecords {
    int rows = 0;
    @try {
        NSString *dbPath = [self getDBPath];

        if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

            NSString *strSQL;
            strSQL = @"SELECT COUNT(*) FROM MYTABLE";
            const char *sql = (const char *) [strSQL UTF8String];
            sqlite3_stmt *stmt;

            if (sqlite3_prepare_v2(database, sql, -1, &stmt, NULL) == SQLITE_OK) {

                // THIS IS WHERE IT FAILS:
                if (SQLITE_DONE!=sqlite3_step(stmt) ) {

                    NSAssert1(0,@"Error when counting rows  %s",sqlite3_errmsg(database));

                } else {
                    rows = sqlite3_column_int(stmt, 0);
                    NSLog(@"SQLite Rows: %i", rows);
                }
                sqlite3_finalize(stmt);
            }
            sqlite3_close(database);
        }
    }
    @catch (NSException * e) {
        NSLog(@"Error Counting");
    }
}

推荐答案

我遇到了一个解决方案,使用我上面的代码,只需将 step 语句替换为下面的代码:

I came across a solution, using my code above, just replacing the step statement with the code below:

if (sqlite3_step(stmt) == SQLITE_ERROR) {
    NSAssert1(0,@"Error when counting rows  %s",sqlite3_errmsg(database));
} else {
    rows = sqlite3_column_int(stmt, 0);
    NSLog(@"SQLite Rows: %i", rows);
}

这篇关于计算 SQLite 数据库中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆