计算 SQLite 数据库中的行数
我正在尝试使用以下代码来计算 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我遇到了一个解决方案,使用上面的代码,只需用下面的代码替换步骤语句:
I came across a solution, using my code above, just replacing the step statement with the code below:
这通常对我有用
}
HTH
This usually works for me
}
HTH
没有 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.
我想我应该在这里花两分钱,因为有一个表达式可以计算数据库中的行数,我在使用 php 脚本处理 MySQL 数据库时总是使用它。我在一个 ios 应用程序中测试了它,它也在那里可用:
不需要花哨的循环计数器。顺便说一句,如果您使用自动增量 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:
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.
您必须单独计算每个表的数量。一些伪代码:
You'll have to count of each table individually. Some pseudo code: