计算 SQLite 数据库中的行数

发布于 2024-11-06 19:02:39 字数 1089 浏览 1 评论 0原文

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

- (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");
    }
}

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");
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

谎言月老 2024-11-13 19:02:39

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

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);
}

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);
}
溇涏 2024-11-13 19:02:39

这通常对我有用

- (NSInteger )numberRecordsForTable:(NSString *)table {
NSInteger numTableRecords = -1;
if (sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
    NSString *sqlStatement = [NSString stringWithFormat: @"select count(*) from %@", table];
    const char *sql = [sqlStatement cStringUsingEncoding:NSUTF8StringEncoding];
    if(sqlite3_prepare_v2(database, sql, -1, &sqlClause, NULL) == SQLITE_OK) {          
        while(sqlite3_step(sqlClause) == SQLITE_ROW) {
            numTableRecords = sqlite3_column_int(sqlClause, 0);
        }
    }
    else {
        printf("could not prepare statement: %s\n", sqlite3_errmsg(database));
    }
}
else {
    NSLog(@"Error in Opening Database File");
}
sqlite3_close(database);
return numTableRecords; 

}

HTH

This usually works for me

- (NSInteger )numberRecordsForTable:(NSString *)table {
NSInteger numTableRecords = -1;
if (sqlite3_open([self.dbPath UTF8String], &database) == SQLITE_OK) {
    NSString *sqlStatement = [NSString stringWithFormat: @"select count(*) from %@", table];
    const char *sql = [sqlStatement cStringUsingEncoding:NSUTF8StringEncoding];
    if(sqlite3_prepare_v2(database, sql, -1, &sqlClause, NULL) == SQLITE_OK) {          
        while(sqlite3_step(sqlClause) == SQLITE_ROW) {
            numTableRecords = sqlite3_column_int(sqlClause, 0);
        }
    }
    else {
        printf("could not prepare statement: %s\n", sqlite3_errmsg(database));
    }
}
else {
    NSLog(@"Error in Opening Database File");
}
sqlite3_close(database);
return numTableRecords; 

}

HTH

百善笑为先 2024-11-13 19:02:39

没有 SQL 表达式来计算数据库中的行数:您可以计算每个表中的行数,然后将它们相加。

There is no SQL expression to count rows in a database: you can count rows in a every table and then add them up.

风渺 2024-11-13 19:02:39

我想我应该在这里花两分钱,因为有一个表达式可以计算数据库中的行数,我在使用 php 脚本处理 MySQL 数据库时总是使用它。我在一个 ios 应用程序中测试了它,它也在那里可用:

sqlite3 *database;
if(sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK)
{
    NSString *sql = @"select count(*) from today";
    sqlite3_stmt *selectStatement;
    int returnValue = sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectStatement, NULL);
    if (returnValue == SQLITE_OK) 
    {
        if(sqlite3_step(selectStatement) == SQLITE_ROW)
        {
            numrows= sqlite3_column_int(selectStatement, 0);
        }
    }
    sqlite3_finalize(selectStatement);
    sqlite3_close(database);
}

不需要花哨的循环计数器。顺便说一句,如果您使用自动增量 int 作为主键。它的工作方式与数组的键略有不同。在一个 n 项长的数组中,有效的数组元素在数据库中是从 0 到 n-1,关键字段是从 1 到 n,如果您记住这一点,就足够简单了。

I thought I'd trow in my two cents here as there is an expression to count rows in a database, I use it when dealing with MySQL databases using php scripts all the time. and I tested it in an ios app it's available in there too behold:

sqlite3 *database;
if(sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK)
{
    NSString *sql = @"select count(*) from today";
    sqlite3_stmt *selectStatement;
    int returnValue = sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectStatement, NULL);
    if (returnValue == SQLITE_OK) 
    {
        if(sqlite3_step(selectStatement) == SQLITE_ROW)
        {
            numrows= sqlite3_column_int(selectStatement, 0);
        }
    }
    sqlite3_finalize(selectStatement);
    sqlite3_close(database);
}

no need for a fancy loop counter thing. btw if your using an auto increment int for the primary key. it works just slightly different then an array's key. where as in an array that is n items long the valid array elements are from 0 to n-1 in a database the key field is from 1 to n simple enough to work around if you just keep that in mind.

同尘 2024-11-13 19:02:39
-(void)databaseRecordCount{
    int rows = 0;
    @try {
        sqlite3 *database;
        NSString *filePath = [self databaseDocumentsFilePath];
        if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
            NSString *query = @"SELECT * FROM MYTABLE";
            sqlite3_stmt *compiledStatement;
            if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) != SQLITE_OK)
                NSLog(@"Error while creating detail view statement. '%s'", sqlite3_errmsg(database));
            if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, nil) == SQLITE_OK) {
                while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                    rows++;
                }
                sqlite3_finalize(compiledStatement);
            }
            sqlite3_close(database);
        }
    }
    @catch (NSException * e) {
        NSLog(@"Error Counting");
    }
    NSLog(@"SQLite Rows: %i", rows);
    NSUserDefaults *userDefaults;
    userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:rows forKey:@"databaseRecordCount"];
    [userDefaults synchronize];
}
-(void)databaseRecordCount{
    int rows = 0;
    @try {
        sqlite3 *database;
        NSString *filePath = [self databaseDocumentsFilePath];
        if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
            NSString *query = @"SELECT * FROM MYTABLE";
            sqlite3_stmt *compiledStatement;
            if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, NULL) != SQLITE_OK)
                NSLog(@"Error while creating detail view statement. '%s'", sqlite3_errmsg(database));
            if(sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, nil) == SQLITE_OK) {
                while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                    rows++;
                }
                sqlite3_finalize(compiledStatement);
            }
            sqlite3_close(database);
        }
    }
    @catch (NSException * e) {
        NSLog(@"Error Counting");
    }
    NSLog(@"SQLite Rows: %i", rows);
    NSUserDefaults *userDefaults;
    userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:rows forKey:@"databaseRecordCount"];
    [userDefaults synchronize];
}
乖乖 2024-11-13 19:02:39

您必须单独计算每个表的数量。一些伪代码:

sql = "SELECT name FROM sqlite_master" WHERE type = 'table'
tables() = GetRows(sql)

Dim total As Integer
For Each t As String in tables
  sql = "SELECT COUNT(*) FROM " + t
  total = total + GetValue(sql)
Next

Show(total)

You'll have to count of each table individually. Some pseudo code:

sql = "SELECT name FROM sqlite_master" WHERE type = 'table'
tables() = GetRows(sql)

Dim total As Integer
For Each t As String in tables
  sql = "SELECT COUNT(*) FROM " + t
  total = total + GetValue(sql)
Next

Show(total)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文