我想这应该是相当简单的,因为我是Xcode,Objective-C和SQLite的新手,我只想尝试一个简单的教程。
我复制了" sampled.sql"文件到目录,这是连接的代码:
-(NSMutableArray *) authorList {
theauthors = [[NSMutableArray alloc] initWithCapacity:10];
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"sampledb.sql"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(@"An error has occured: %s", sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM verb";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement 1: %s", sqlite3_errmsg(db));
} else {
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Author * author = [[Author alloc] init];
author.verb_nutid = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
//author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
[theauthors addObject:author];
}
}
sqlite3_finalize(sqlStatement);
}
@catch (NSException *exception) {
NSLog(@"Problem with prepare statement 2: %s", sqlite3_errmsg(db));
}
@finally {
sqlite3_close(db);
return theauthors;
}
}
数据库文件:
BEGIN TRANSACTION
CREATE TABLE"动词" (' ID' INTEGER PRIMARY KEY AUTOINCREMENT,' verba' TEXT,' verbb' TEXT); INSERT INTO'动词'价值观......
等等......
但我收到错误:
准备语句1的问题:文件已加密或不是数据库
非常感谢帮助! ( - :
答案 0 :(得分:1)
尝试将sampledb.sql
写入documents directory
而不是bundle directory
:
// Getting the documents directory path
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Getting your db's path
NSString *dbPath = [docsDir stringByAppendingPathComponent:@"sampledb.sql"];
没有办法写入bundle目录,因为它的代码是用SSL证书签名的。但文件目录不是。