在OSX中更新sqlite3数据库的列

时间:2012-12-26 08:22:10

标签: objective-c macos cocoa sqlite

我是OSX App开发的新手。我正在尝试在sqlite数据库中存储4个值(Date,value1,value2,value3)。如果使用现有日期输入新记录,我需要更新记录的最后3个字段。我该怎么做。我在下面给出了插入数据库的代码

- (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 
  {

  }
}

为了满足这一要求,还包括哪些内容?

1 个答案:

答案 0 :(得分:5)

首先检查已存在的日期

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);
        }
    }