有没有办法在Objectiveite中获得SQLite中表的大小?

时间:2015-04-03 17:18:07

标签: objective-c sqlite

我觉得这样做并不容易?获取每个托管对象,获取链接到它的所有对象,并计算转换变量的字节数?

1 个答案:

答案 0 :(得分:0)

好的,我找到了获取db统计数据所需的解决方案。

正如所建议的那样,我直接使用了带有length()函数的SQL查询。然后我可以循环以计算总大小(以字节为单位)。

首先,在您的XCode项目中,包括' libsqlite3.0.dylib'

然后,导入lib:

#import <sqlite3.h>

最后,实施可能是:

float size;
sqlite3* dbHandle;
NSArray *paths =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString* dbFile = [documentsDirectory stringByAppendingPathComponent:@"mybase.sqlite"];

sqlite3_config(SQLITE_CONFIG_SERIALIZED);

int result = sqlite3_open([dbFile UTF8String], &dbHandle);
if (result != SQLITE_OK) {
    NSLog(@"Failure in connecting to the database with result %d",result);
}
else {
    NSLog(@ "Successfully opened connection to DB") ;

    NSString    *query  =   @"SELECT length(HEX(zmyField))/2 FROM zmyTable";
// You have to append 'z' to table and name field due to SQLite naming convention (cf.https://softwareengineering.stackexchange.com/questions/178994/why-do-core-data-sqlite-table-columns-start-with-z)

    const char *sql3 = [[NSString stringWithFormat:query] cStringUsingEncoding:NSUTF8StringEncoding];

    NSMutableArray *results = [NSMutableArray array];

    sqlite3_stmt *sql1Statement;
    int returnCode;
    if(sqlite3_prepare_v2(dbHandle, sql3, -1, &sql1Statement, NULL) != SQLITE_OK)
    {
        NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(dbHandle));
    }
    else
    {

        while ((returnCode = sqlite3_step(sql1Statement)) == SQLITE_ROW) {
            NSLog(@"SIZE : %f",sqlite3_column_double(sql1Statement, 0));
            size+=sqlite3_column_double(sql1Statement, 0);
        }
        if (returnCode != SQLITE_DONE)
            NSLog(@"Problem with step statement: %s", sqlite3_errmsg(dbHandle));

        sqlite3_finalize(sql1Statement);
    }
}
NSLog(@"TOTAL SIZE for myField in my Table : %f",size);

要获取总数据库大小或逐个表,甚至逐个字段,您可以使用SQLite指令列出所有表和字段名称。 然后将length()函数应用于循环结果:

对于表格列表:

SELECT name FROM sqlite_master WHERE type='table'

对于字段:

PRAGMA table_info('myTable')

参考:

http://www.priyaontech.com/2011/09/intro-to-sqlite-for-ios-developers/

How do I find the length (size) of a binary blob in sqlite

https://softwareengineering.stackexchange.com/questions/178994/why-do-core-data-sqlite-table-columns-start-with-z

How to get a list of column names on sqlite3 / iPhone?