1

我是 OSX 应用程序开发的新手。我正在尝试在 sqlite 数据库中存储 4 个值(日期、值 1、值 2、值 3)。如果使用现有日期输入新记录,我需要更新记录的最后 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 
  {

  }
}

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

4

1 回答 1

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);
        }
    }
于 2012-12-26T08:37:30.590 回答