sqlite DB を使用するアプリケーションを 1 つ作成します。私には1つの問題があり、それはいつでもアプリケーションを実行して、テーブルsqliteにNSDictionaryを追加します。一度sqliteをチェックして、テーブルsqliteにデータが存在する場合は追加しないでください。
この私のコード:
ViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface ViewController : UIViewController
{
sqlite3 * database;
}
@end
ViewController.m
#import "ViewController.h"
#define DatabaseName @"data.sqlite"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *idd = [NSArray arrayWithObjects:@"122",@"234",@"453", nil];
NSArray *name = [NSArray arrayWithObjects:@"janatan",@"fred",@"john", nil];
NSArray *age = [NSArray arrayWithObjects:@"23",@"35",@"12", nil];
NSArray *sex = [NSArray arrayWithObjects:@"male",@"male",@"male", nil];
for (int i = 0; i < [idd count]; i++)
{
NSString * a = [idd objectAtIndex:i];
NSString * b = [name objectAtIndex:i];
NSString * c = [age objectAtIndex:i];
NSString * d = [sex objectAtIndex:i];
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:a,@"id",b,@"name",c,@"age",d,@"sex", nil];
NSString *query = [NSString stringWithFormat:@"insert into table1 (id,name,age,sex) values('%@','%@','%@','%@')",[dic objectForKey:@"id"],[dic objectForKey:@"name"],[dic objectForKey:@"age"],[dic objectForKey:@"sex"]];
NSLog(@"%@",query);
[self executeQuery:query];
}
}
-(NSString *) dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DatabaseName]);
return [documentsDirectory stringByAppendingPathComponent:DatabaseName];
}
/*==================================================================
METHOD FOR INSERTING DATA IN DATABASE
==================================================================*/
-(void)executeQuery:(NSString *)query
{
//NSLog(@"QUERY : %@",query);
sqlite3_stmt *statement;
if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
{
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) != SQLITE_DONE)
{
sqlite3_finalize(statement);
}
}
else
{
NSLog(@"query Statement Not Compiled");
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
else
{
NSLog(@"Data not Opened");
}
}
@end
NSDictionary
また、たとえば配列が変更されたときに欲しいのは、辞書の増加値の更新 sqlite の完了です。
説明してください。