2015-04-03 29 views
-1

我觉得有没有简单的方法来做到这一点?获取每个ManagedObject,获取链接到它的所有对象,并计算转换后的变量的字节数?有没有办法在Objective-C中获取SQLite中的表的大小?

+0

正是你在找什么规模? – rmaddy 2015-04-03 18:57:41

+0

https://www.sqlite.org/lang_aggfunc.html#count – 2015-04-03 20:23:05

+0

我在这里得到了我的答案:http://stackoverflow.com/questions/250940/how-do-i-find-the-length-size-对的一二进制BLOB功能于sqlite的。我将总结查询每个字段后返回的所有值。 – 2015-04-07 07:11:42

回答

0

好吧,我找到了我需要的解决方案来获取我的数据库统计数据。

如上所述,我直接用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?

相关问题