SQLite3 DB に 3 つのデータを追加しようとしています。チュートリアルの助けを借りて、私はほとんどそこにいます。以下は私のコードです。
から期待されるものを受け取っていNSLogs
ます。問題なくDBを見つけ、問題なくDBに送信するステートメントをコンパイルしますが、アプリに到達するsqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK
と、データがに追加されることを期待していますDB
が、そうではなく、表示されることも期待していますaUIAlertView
ユーザーに ERROR または SUCCESS を伝えます。私が見ていないものを見ていただければ幸いです。
- (IBAction)addData:(id)sender {
NSString *n = [[NSString alloc] initWithString:[name text]];
NSString *a = [[NSString alloc] initWithString:[age text]];
NSString *c = [[NSString alloc] initWithString:[color text]];
NSLog(@"%@ - %@ - %@",n,a,c);
[self insertDataName:n Age:a Color:c];
}
これによりNSLog
、期待どおりのテキスト プロパティが返されます。
- (IBAction)hide:(id)sender {
[name resignFirstResponder];
[age resignFirstResponder];
[color resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
DBName = @"mydatabase.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentsPaths objectAtIndex:0];
DBPath = [documentsDir stringByAppendingPathComponent:DBName];
}
-(void)checkAndCreateDB {
BOOL Success;
NSFileManager *fileManager = [NSFileManager defaultManager];
Success = [fileManager fileExistsAtPath:DBPath];
if(Success) {
NSLog(@"DB Found");
return;
}
NSLog(@"DB Not Found");
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];
[fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
}
これNSLog
は戻りますDB Found
-(void)insertData Name:(NSString*)n Age:(NSString*)a Color:(NSString*)c {
[self checkAndCreateDB];
sqlite3 *database;
if (sqlite3_open([DBPath UTF8String],&database)==SQLITE_OK) {
NSString *statement;
sqlite3_stmt *compliedstatement;
statement = [[NSString alloc] initWithFormat:@"insert into table1 values ('%@', '%@', '%@')",n,a,c];
const char *sqlstatement = [statement UTF8String];
NSLog(@"%@",statement);
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
NSAssert1(0, @"Error by inserting '%s'", sqlite3_errmsg(database));
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error by inserting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[AlertOK show];
}
else {
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Data successfully inserted" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[AlertOK show];
}
}
sqlite3_finalize(compliedstatement);
}
sqlite3_close(database);
}
そして、NSLog
上記の最後の表示insert into table1 values ('n', 'a', 'c')
は、期待どおりに表示されます。
挿入時に何かがうまくいかず、それを理解できません。
参考までに、DB は SQLiteManager を使用して作成されました。以下SS: