从sqlite3表中提取数据

时间:2013-11-07 02:44:13

标签: ios sqlite

当用户尝试在同一日期(日期为主键)创建两个或更多条目时,我试图从特定行中提取数据。

在我的.h文件中

@interface PunchClock : UIViewController{

    sqlite3 *db;

}
-(NSString *) filePath;
-(void)openDB;
-(void) createTable: (NSString *) tableName
         withField1:(NSString *) field1
         withField2:(NSString *) field2
         withField3:(NSString *) field3;

在我的.m文件中(不确定是否需要以下代码来破译我的问题,但不管怎么说都发布了)

-(void) createTable: (NSString *) tableName
         withField1:(NSString *) field1
         withField2:(NSString *) field2
         withField3:(NSString *) field3;
{
    char *err;
    NSString *sql=[NSString stringWithFormat:@" CREATE TABLE IF NOT EXISTS '%@'('%@' TEXT PRIMARY KEY,'%@' TEXT,'%@' TEXT);",tableName,field1,field2,field3];

    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK){
        sqlite3_close(db);
        NSAssert(0, @"Could not create table");
    }else{
        NSLog(@"table created");
    }
}



-(NSString *) filePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"PunchClock.sql"];

    return path;
}

-(void)openDB{
    if(sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK){
        sqlite3_close(db);
        NSAssert(0, @"Database failed to open");
    }else{
        NSLog(@"database opened");
    }
}

现在这就是我的问题所在。我可以成功插入数据但是当用户在同一天输入数据时(字段1是日期,我的主键)我想将数据拉出来更新它并更新表。我卡在我从行中提取数据的部分(检查注释以澄清):

- (IBAction)save:(id)sender {
{
        NSString *HoursWorked = [NSString stringWithFormat:@"%f", final];
        NSString *TotalEarned = [NSString stringWithFormat:@"%f", paidFloat];

        NSString *sql = [NSString stringWithFormat:@"INSERT INTO HourLog ('Date', 'HoursWorked','TotalEarned') VALUES ('%@', '%@', '%@')", dbDate , HoursWorked, TotalEarned];

        char *err;
        if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK){
            sqlite3_close(db);
           // NSAssert(0,@"Could not update table");

            //primary key already exists

            [self openDB];
            NSString *currentHoursWorked = HoursWorked;
            NSString *currentTotalEarned = TotalEarned;
            NSString *previousHoursWorked;
            NSString *previousTotalEarned;


            NSString *sql = [NSString stringWithFormat:@"SELECT FROM HourLog WHERE Date = '%@'", dbDate];

            sqlite3_stmt *statement;
            // the if statement below is not being executed for some reason? Can someone see why?
            if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK){

                char *field2 = (char *) sqlite3_column_text(statement, 1);
                NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
                previousHoursWorked = field2Str;

                char *field3 = (char *) sqlite3_column_text(statement, 2);
                NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];
                previousTotalEarned = field3Str;

            }

            sqlite3_finalize(statement);

           sqlite3_close(db);

            NSLog(@"%@", previousHoursWorked); 
            NSLog(@"%@", previousTotalEarned);



        }else{
            NSLog(@"table updated");

        }

    }





}

1 个答案:

答案 0 :(得分:1)

有几点想法:

  1. 如果您的sqlite3_errmsg失败,我就不会记录sqlite3_prepare_v2,我认为会这样做,因为您没有指定从SELECT返回哪些字段言。

    每当您遇到SQLite错误时,都应确保记录sqlite3_errmsg

  2. 您也永远不会调用sqlite3_step来实际执行SELECT语句。

  3. 最后,sqlite3_column_text返回从0开始的索引,而不是从1开始的索引,因此第一列为0,第二列为1。正如the docs所说,“结果集的最左边的列的索引为0。”

  4. 所以,我原本以为你会想要这样的东西:

    // replace column_a and column_b with your column names
    
    NSString *sql = [NSString stringWithFormat:@"SELECT column_a, column_b FROM HourLog WHERE Date = '%@'", dbDate];
    
    sqlite3_stmt *statement;
    
    if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK){
    
        int rc;
        if ((rc = sqlite3_step(statement)) == SQLITE_ROW) {
            char *field2 = (char *) sqlite3_column_text(statement, 0);
            NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
            previousHoursWorked = field2Str;
    
            char *field3 = (char *) sqlite3_column_text(statement, 1);
            NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];
            previousTotalEarned = field3Str;
        } else if (rc != SQLITE_DONE) {
            NSLog("%s: sqlite3_step failed: %s", __FUNCTION__, sqlite3_errmsg(db));
        }    
    } else {
        NSLog("%s: sqlite3_prepare_v2 failed: %s", __FUNCTION__, sqlite3_errmsg(db));
    }
    

    顺便说一句,虽然你可以先SELECT来查看是否有匹配,如果找到匹配则执行UPDATE,如果没有则执行INSERT,可能会执行此操作只是更容易使用SQLite INSERT OR REPLACE语法。请参阅INSERT documentation