我正在尝试从 sqlite 数据库中提取数据。我添加了“libsqlite3.0.dylib”文件并将创建的 sqlite DB 复制到我的应用程序文件夹中。我在 appdelegate 文件中创建了两个方法。他们是
//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 文件中添加了一种方法。那是
-(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
有人告诉我做什么吗??????
提前致谢...........