2015-04-03 81 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?

相關問題