我创建了一个在其中使用 sqlite DB 的应用程序。我有一个问题,任何时候运行我的应用程序都会在我的表 sqlite 中添加 NSDictionary。我想检查一次 sqlite,如果表 sqlite 中存在数据,则不要添加,否则添加它。
这是我的代码:
视图控制器.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface ViewController : UIViewController
{
sqlite3 * database;
}
@end
视图控制器.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 完成。
请解释一下。