「libsqlite3.0.dylib」ファイルを追加し、作成したsqlite DBをアプリフォルダーにコピーしました。appdelegate ファイルに 2 つのメソッドを作成しました。彼らです
//To copy DB
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSLog(@"DB File %@ does not exists", dbPath);
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"tms.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
NSLog(@"Successfully copied db file to path %@", dbPath);
if (!success)
NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
} else {
NSLog(@"DB File %@ already exists", dbPath);
}
}
//To get DB path
-(NSString *)getDBPath{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
return [documentDir stringByAppendingPathComponent:@"sampleDB.sqlite"];
}
didFinishLaunchingWithOptions で copyDatabaseIfNeeded() を呼び出し、ViewController.m ファイルに 1 つのメソッドを追加しました。あれは
-(void)Display
{
SqlitAppDelegate *appDelegate=(SqlitAppDelegate *)[UIApplication sharedApplication].delegate;
NSString *dbPath=[appDelegate getDBPath];
if (sqlite3_open([dbPath UTF8String], &myDB) == SQLITE_OK)
{
NSLog(@"Database opned successflly");
const char *sql = "select * from sampleTable";
NSLog(@"%s",sql);
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(myDB, sql, -1, &selectstmt, NULL) == SQLITE_OK)
NSLog(@"Prepared successfully");
else
{
NSLog(@"Preparation failed");
NSLog(@"%s",sqlite3_errmsg(myDB));
NSLog(@"%d",sqlite3_errcode(myDB));
}
}
else
NSLog(@"Couldn't open database");
}
私は didViewLoad メソッドでこのメソッドを呼び出しました。
次の出力が得られます。
- 2013-03-20 12:02:24.026 SqliteSample2[951:11303] データベースが正常に開かれました
- 2013-03-20 12:02:24.027 SqliteSample2[951:11303] sampleTable から * を選択
- 2013-03-20 12:02:24.028 SqliteSample2[951:11303] 準備に失敗しました
- 2013-03-20 12:02:24.029 SqliteSample2[951:11303] そのようなテーブルはありません: sampleTable
- 2013-03-20 12:02:24.029 SqliteSample2[951:11303] 1
誰か私が何をしているか教えてください??????
前もって感謝します...........