【问题标题】:Is there a way to get the size of a table in SQLite in objective-C?有没有办法在objective-C中获取SQLite中表的大小?
【发布时间】:2015-04-03 17:18:07
【问题描述】:

我觉得没有简单的方法可以做到这一点?获取每个ManagedObject,获取与其链接的所有对象,统计转换后变量的字节数?

【问题讨论】:

标签: objective-c sqlite


【解决方案1】:

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

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

首先,在您的 XCode 项目中,包含“libsqlite3.0.dylib”

然后,导入库:

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

要获取总 db 大小,或逐个表,甚至逐个字段,您可以使用 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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多