2013-03-28 94 views
0

我已經從包中將預填充的sqlite數據庫複製到庫路徑。現在,當我嘗試執行查詢時,它不讀取數據庫。我無法讀取我的預先存在的sqlite數據庫

代碼複製數據庫:

-(void)createDatabase 
{ 
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; 
    NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"gre.db"]; 


    if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) { 
     // database doesn't exist in your library path... copy it from the bundle 
     NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"gre.db"]; 
     NSError *error = nil; 

     if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) { 
      NSLog(@"Error: %@", error); 
     } 
    } 
} 

我把這個從我applicationDidFinishLaunchLaunchingWithOptions和數據庫複製

這是我的查詢讀取數據庫:

-(void)readDatabase 
{ 
    wordlist = [[NSMutableArray alloc] init]; 
    NSString *query =[NSString stringWithFormat:@"SELECT word FROM words WHERE word LIKE '%@%%'",selectedWord]; 
    sqlite3_stmt *statement; 
    if (sqlite3_prepare_v2(database, [query UTF8String],-1, &statement, nil) == SQLITE_OK) 
    { 
     while (sqlite3_step(statement) == SQLITE_ROW) 
     { 
      char *id1 = (char *)sqlite3_column_text(statement, 0); 
      [wordlist addObject:[NSString stringWithFormat:@"%s",id1]]; 
     } 
    } 
    sqlite3_finalize(statement); 

    NSLog(@"%@",wordlist); 

} 

現在控制不進入*while (sqlite3_step(statement) == SQLITE_ROW)*循環 因此不顯示數據。

+0

在documentDirectory數據庫中是否爲空? – Yashesh 2013-03-28 09:42:28

+0

您是否嘗試從設備中取回數據(或者在模擬器中查看它)以驗證內容是否真正被複制? – gaige 2013-03-28 09:47:06

+0

否。數據庫已正確複製到庫路徑。但它並沒有進入.... while(sqlite3_step(statement)== SQLITE_ROW)! – Chiran 2013-03-28 09:48:58

回答

0

使用此代碼並檢查數據庫是否連接並正確打開,然後從中獲取數據。希望這會有所幫助。

-(void)readDatabase 
    { 
     // Set path 
     NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//(customize the path based on ur database location) 

     NSString *docsDir = [dirPaths objectAtIndex:0]; 

     NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"database.db"]]; 
    const char *dbpath = [databasePath UTF8String]; 


     //Checking connection 
     if (sqlite3_open(dbpath, &SQLitedatabase) == SQLITE_OK) 
       { 
       wordlist = [[NSMutableArray alloc] init]; 
       NSString *query =[NSString stringWithFormat:@"SELECT word FROM words WHERE word LIKE '%@%%'",selectedWord]; 
       sqlite3_stmt *statement; 
       if (sqlite3_prepare_v2(database, [query UTF8String],-1, &statement, nil) == SQLITE_OK) 
       { 
       while (sqlite3_step(statement) == SQLITE_ROW) 
       { 
       char *id1 = (char *)sqlite3_column_text(statement, 0); 
       [wordlist addObject:[NSString stringWithFormat:@"%s",id1]]; 
       } 
       } 
       sqlite3_finalize(statement); 

       } 
       } 
    } 

,並確保數據庫的初始化也是這樣......

#import <sqlite3.h> 

NSString *databasePath; 

sqlite3 *SQLiteDataBaseDB; 

@implementation DatabaseManager 
+(void)initializeDb 
{ 
    NSString *docsDir; 
    NSArray *dirPaths; 

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    docsDir = [dirPaths objectAtIndex:0]; 

    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"database.db"]]; 

    NSFileManager *filemgr = [NSFileManager defaultManager]; 

    if ([filemgr fileExistsAtPath: databasePath ] == NO) 
    { 
     const char *dbpath = [databasePath UTF8String]; 

     if (sqlite3_open(dbpath, &SQLiteDataBaseDB) == SQLITE_OK) 
     { 
      char *errMsg; 
      //SELECT name FROM sqlite_master WHERE name=USER_VIDEO_INFO 

      const char *sql_stmt = "CREATE TABLE IF NOT EXISTS USER_VIDEO_INFO (userIdentifier TEXT, managerName TEXT, videoPath TEXT, videoName TEXT, shotDate TEXT, session TEXT, videoCategory TEXT)"; 

      if (sqlite3_exec(SQLiteDataBaseDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) 
      { 
       NSLog(@"Failed to create table"); 
      } 

      sqlite3_close(SQLiteDataBaseDB); 

     } 
     else 
     { 
      NSLog(@"Failed to open/create database"); 
     } 

      } 

} 

並檢查身體創建DB或不喜歡這個......

enter image description here

+0

嘿,非常感謝您的代碼完美! – Chiran 2013-03-28 10:39:07

+0

但在我的情況下,我不需要進行初始化?!我正在使用預先存在的sqlite數據庫。 – Chiran 2013-03-28 11:10:24

0

如果您的數據庫文件位於資源目​​錄中,請嘗試以下代碼:

-(NSString*)databasePath 
{ 
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:"gre" forType:"db"]; 
    return dbPath; 
} 

其實你正在爲你的數據庫提取錯誤的路徑。

0

您可以測試以下代碼。這對我來說可以。

if (userDB == NULL) { 
     sqlite3 *newDBconnection; 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *path = [documentsDirectory stringByAppendingPathComponent:@"gre.sqlite"]; 

     // Check if the SQL database has already been saved to the users phone, if not then copy it over 
     BOOL success; 

     // Create a FileManager object, we will use this to check the status 
     // of the database and to copy it over if required 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 

     // Check if the database has already been created in the users filesystem 
     success = [fileManager fileExistsAtPath:path]; 

     // If the database already exists then dont do anything 
     if(!success) 
     { 
      NSLog(@"not success"); 
      // If not then proceed to copy the database from the application to the users filesystem 

      // Get the path to the database in the application package 
      NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pero1.sqlite"]; 

      // Copy the database from the package to the users filesystem 
      [fileManager copyItemAtPath:databasePathFromApp toPath:path error:nil]; 

     } 
     NSLog(@"success"); 

     if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) { 
      //NSLog(@"Database Successfully Opened :)"); 
      userDB = newDBconnection; 
     } else { 
      NSLog(@"Error in opening database :("); 
      userDB = NULL; 
    return; 
     } 
    } 
    wordlist = [[NSMutableArray alloc] init]; 

NSString *query = [NSString stringWithFormat:@"SELECT word FROM words WHERE word LIKE '%@%%'",selectedWord]; 
     NSLog(@"query: %@",query); 

     const char *sqlStatement = [query UTF8String]; 
     sqlite3_stmt *compiledStatement; 
    NSString *listFromDB = @""; 
     if(sqlite3_prepare_v2(userDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
     { 
      // Loop through the results and add them to the feeds array 
      while(sqlite3_step(compiledStatement) == SQLITE_ROW) { 
       // Read the data from the result row 
       char *id1 = (char *)sqlite3_column_text(statement, 0); 
      [wordlist addObject:[NSString stringWithFormat:@"%s",id1]]; 

       } 
     } 
     // Release the compiled statement from memory 
     sqlite3_finalize(compiledStatement); 
+0

這個工作也不錯!謝謝Anum。 – Chiran 2013-03-28 11:08:37

+0

你可以upvote我的答案,如果它幫助你ü:) – NightFury 2013-03-28 12:14:46

0

Ganapathy你的代碼工作太棒了!但不是在每個選擇查詢之前打開數據庫,而是在每次選擇查詢之前打開數據庫,而不是在每個選擇查詢之前打開數據庫,而是在我的代碼中嘗試了這一點,它的工作原理類似於魅力!

-(void)createDatabase 
{ 
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; 
    NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"gre.db"]; 


    if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) { 
     // database doesn't exist in your library path... copy it from the bundle 
     NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"gre.db"]; 
     NSError *error = nil; 

     if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) { 
      NSLog(@"Error: %@", error); 
     } 
    } 

    //Open Database 
    if (sqlite3_open([targetPath UTF8String], &database) != SQLITE_OK) 
    { 
     sqlite3_close(database); 
     NSLog(@"Failed to open db."); 
    } 

}