由于某种原因,以下代码不会在我的sqlite数据库中存储任何数据。返回码是SQLITE_DONE(101)所以它没有给我任何错误消息。该方法被多次调用以填充数据库中的几行。谁能看到我出错的地方?
- (void)storePersonInDatabase:(Person *)person {
const char *sql = "INSERT INTO PERSON (ID, NAME, NOTES, ADDRESS, PROMOTED, VEGETARIAN) values (?, ?, ?, ?, ?, ?)";
sqlite3_stmt *statement;
// Prepare the data to bind.
NSData *imageData = person.imageData;
NSString *personId = [person.personId stringValue];
NSString *personName = person.name;
NSString *address = person.address;
NSString *notes = person.notes;
NSString *isVegetarian = (person.isVegetarian) ? @"1" : @"0";
NSString *isPromoted = (person.isPromoted) ? @"1" : @"0";
// Prepare the statement.
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// Bind the parameters (note that these use a 1-based index, not 0).
sqlite3_bind_text(statement, 1, [personId UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [personName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, [notes UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, [address UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 5, [isPromoted UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 6, [isVegetarian UTF8String], -1, SQLITE_TRANSIENT);
}
// Execute the statement.
int returnCode = sqlite3_step(statement);
if (returnCode != SQLITE_DONE) {
// error handling...
NSLog(@"An error occoured");
}
//这就是我设置db
的方法NSString *sqliteDb = [[NSBundle mainBundle] pathForResource:@"Persons" ofType:@"sqlite"];
if(sqlite3_open([sqliteDb UTF8String], &database) != SQLITE_OK){
NSLog(@"Unable to open database");
}
答案 0 :(得分:2)
正如一些人所建议的那样,您需要将数据库复制到项目包之外的位置。在那里,您可以根据需要进行读写,否则每次尝试运行“storePersonInDatabase”方法时,基本上只需创建新数据库。
在尝试与数据库交互之前,您应该执行Daij-Djan提供的相同检查。您还应该在某处保存数据库的位置或名称,以便于访问和文件检查。
答案 1 :(得分:1)
您将展示如何尝试在应用包中打开sqlite文件
您无法写入您的应用包
应用包是只读的
你需要将它复制到你可以写的地方。听起来应该去图书馆/文件。
伪代码是:
if(!sqlite_already_in_library) {
[file_manager copyFileFrom:sqlite-in-bundle to:sqlite-in-library_path];
}