Reputation: 573
I am new to OSX App development.I am trying to store 4 values (Date, value1, value2, value3) in sqlite databse. I need to update the last 3 fields of a record if a new record is entered with the existing date. How can i do it. My code to insert into database is given below
- (void) addToDatabase:(Day *)sampleDay
{
databasePath = [Database_Access createDirectory];
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
NSString *str= [NSString stringWithFormat:@"INSERT INTO TABLEOBJ (DATE,NIDHIN,PAI,RUBEN ) VALUES ('%@',%li,%li,%li)", sampleDay.date, sampleDay.value1, sampleDay.value2, sampleDay.value3];
const char *sql_stmt = [str UTF8String];
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
}
sqlite3_close(database);
}
else
{
}
}
What all are to be included in order to meet this requirement?
Upvotes: 1
Views: 1059
Reputation: 3905
First check the date already exist or not
if (sqlite3_open(dbpath, &quizDB) == SQLITE_OK)
{
sqlite3_stmt *statement;
// ================Read date with current date value table===================
NSString *readDate = [NSString stringWithFormat: @"SELECT * FROM TABLEOBJ WHERE DATE = %@",sampleDay.date];
const char *readDate_stmt = [readDate UTF8String];
if (sqlite3_prepare_v2(quizDB, readDate_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSString *str;
if (sqlite3_step(statement) == SQLITE_ROW)
{
str = [NSString stringWithFormat:@"INSERT INTO TABLEOBJ (DATE,NIDHIN,PAI,RUBEN ) VALUES ('%@',%li,%li,%li)", sampleDay.date, sampleDay.value1, sampleDay.value2, sampleDay.value3];
}
else
{
str = [NSString stringWithFormat:@"UPDATE TABLEOBJ SET NIDHIN = %li, PAI = %li, RUBEN = %li where DATE = %@", sampleDay.value1, sampleDay.value2, sampleDay.value3,sampleDay.date];
}
// Do the execution steps
sqlite3_finalize(statement);
}
}
Upvotes: 5