Вставка значения int в sqlite с помощью (FMDB с iOS) и его получение: не то, чего мы ждали

Мне немного неловко, так как я трачу весь свой день на эту проблему, в то время как вам это может показаться очень тривиальным,

Как упоминалось в заголовке, я сохраняю значения в sqlite через FMDB (в данном случае это значения 1, 2 или 3).

Когда в другом представлении я подключаюсь к SQLiteDB и получаю свое значение, оно отображает мне странное число (обычно в порядке 144963008), которое не соответствует значению, которое я сохранил.

Используя NSLog(), я вижу, что сохраненное значение — это значение, которое я хочу сохранить.

2014-01-06 12:14:16.677 GDV[11314:70b] the inserted value in column 'idValue' is: 1
2014-01-06 12:14:16.679 GDV[11314:70b] the inserted value in column 'idValue' is: 2
2014-01-06 12:14:16.682 GDV[11314:70b] the inserted value in column 'idValue' is: 3
2014-01-06 12:14:16.689 GDV[11314:70b] current user ID: 1
2014-01-06 12:14:16.690 GDV[11314:70b] idValue retrieve from sqlite: 144963008
2014-01-06 12:14:16.690 GDV[11314:70b] The value does not correpond.
2014-01-06 12:14:16.690 GDV[11314:70b] idValue retrieve from sqlite: 144985232
2014-01-06 12:14:16.690 GDV[11314:70b] The value does not correpond.
2014-01-06 12:14:16.690 GDV[11314:70b] idValue retrieve from sqlite: 144985664
2014-01-06 12:14:16.690 GDV[11314:70b] The value does not correspond.

Полученные здесь значения должны быть соответственно 1, 2 и 3.

Другой метод относительно предмета:

таблица создана

    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [docPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir   stringByAppendingPathComponent:@"UserDatabase.sqlite"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dbPath]) {
        FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
        [database open];
        [database executeUpdate:@"CREATE TABLE userList (id INTEGER  PRIMARY KEY DEFAULT NULL, idValue INTEGER DEFAULT NULL,name TEXT DEFAULT NULL, gender TEXT DEFAULT NULL, age INTEGER DEFAULT NULL, weight INTEGER DEFAULT NULL, tall INTEGER DEFAULT NULL, qq TEXT DEFAULT NULL, email TEXT DEFAULT NULL, phone TEXT DEFAULT NULL, geneA INTEGER DEFAULT NULL, geneB INTEGER DEFAULT NULL, geneDr INTEGER DEFAULT NULL, geneA2 INTEGER DEFAULT NULL, geneB2 INTEGER DEFAULT NULL, geneDr2 INTEGER DEFAULT NULL, compare INTEGER DEFAULT NULL)"];
        [database close];

        //DB for current user
        [database open];
        [database executeUpdate:@"CREATE TABLE currentUser (id INTEGER  PRIMARY KEY DEFAULT NULL,name TEXT DEFAULT NULL, idValue INTEGER DEFAULT NULL)"];
        [database close];
        NSLog(@"DB created");
    } else{
        NSLog(@"DB exist");
    }
    NSLog(@"task finished");

Вставка значений в мои таблицы

        NSDictionary *tempDic = [dataArray objectAtIndex:i];
        NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [docPaths objectAtIndex:0];
        NSString *dbPath = [documentsDir   stringByAppendingPathComponent:@"UserDatabase.sqlite"];

        FMDatabase *database = [FMDatabase databaseWithPath:dbPath];

        // Save or change current user
        [database open];
        [database executeUpdate:@"DELETE FROM currentUser"];
        [database close];

        [database open];
        [database executeUpdate:@"INSERT INTO currentUser (id, name, idValue) VALUES (?, ?, ?)", [NSNumber numberWithInt:0], [NSString stringWithFormat:@"%@", [txt_user_name text]], [NSNumber numberWithInt:[[txt_user_psw text] intValue]]];
        [database close];

        // Save all users
        [database open];
        [database executeUpdate:@"INSERT INTO userList (id, idValue, name, gender, age, weight, tall, qq, email, phone, geneA, geneB, geneDr, geneA2, geneB2, geneDr2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [NSNumber numberWithInt:(int)[tempDic objectForKey:@"id"]*200], [NSNumber numberWithInt:(int)[tempDic valueForKey:@"id"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"name"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"gender"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"age"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"weight"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"tall"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"qq"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"email"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"phone"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneA"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneB"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneDr"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneA2"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneB2"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneDr2"]], nil];
        NSLog(@"the inserted value in column 'idValue' is: %@" ,[tempDic objectForKey:@"id"]);
        [database close];

и, наконец, получение моего значения в другом представлении

    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [docPaths objectAtIndex:0];
    NSString *dbPath = [documentsDir   stringByAppendingPathComponent:@"UserDatabase.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    FMResultSet *results2 = [database executeQuery:@"SELECT * FROM userList"];
    while([results2 next]) {
        NSLog(@"idValue retrieve from sqlite: %d", [results2 intForColumn:@"idValue"]);
        if ([results2 intForColumn:@"idValue"] == myID) {
            NSLog(@"YES");
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneA"]]];
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneB"]]];
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneDr"]]];
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneA2"]]];
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneB2"]]];
            [valueOfCurrentUser addObject:[NSNumber numberWithInt:[results2 intForColumn:@"geneDr2"]]];
        } else{
            NSLog(@"The value does not correpond.");
        }
    }
    [database close];

(Я искренне знаю, что мой код написан ужасно, я совсем новичок в программировании, и я планировал потратить время на его чистку в конце моего проекта.)

Заранее благодарим вас за ваше время,

Искренне


person sebastien FCT    schedule 06.01.2014    source источник
comment
Вы проверили свой файл БД, я думаю, что вы записываете правильное значение, но вставляете неправильное   -  person Retro    schedule 06.01.2014
comment
Спасибо за ваш ответ, есть ли способ проверить наш файл БД? Или вы предлагаете мне регистрировать DBFile, а не значение, которое я вставляю в него?   -  person sebastien FCT    schedule 06.01.2014
comment
NSLog(@%@,[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] должен дать вам путь к каталогу.   -  person Martol1ni    schedule 06.01.2014


Ответы (1)


Благодаря вашим комментариям я трачу на это больше времени, и оказывается, что в некоторых случаях приведение значения как int не будет работать с sqlite, поэтому неправильная часть моего кода была следующей:

// Save all users
        [database open];
        [database executeUpdate:@"INSERT INTO userList (id, idValue, name, gender, age, weight, tall, qq, email, phone, geneA, geneB, geneDr, geneA2, geneB2, geneDr2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [NSNumber numberWithInt:(int)[tempDic objectForKey:@"id"]*200], [NSNumber numberWithInt:(int)[tempDic valueForKey:@"id"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"name"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"gender"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"age"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"weight"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"tall"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"qq"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"email"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"phone"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneA"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneB"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneDr"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneA2"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneB2"]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"geneDr2"]], nil];
        NSLog(@"the inserted value in column 'idValue' is: %@" ,[tempDic objectForKey:@"id"]);
        [database close];

Похоже, что хороший способ - вызвать метод intValue:

// Save all users
        [database open];
        [database executeUpdate:@"INSERT INTO userList (id, idValue, name, gender, age, weight, tall, qq, email, phone, geneA, geneB, geneDr, geneA2, geneB2, geneDr2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [NSNumber numberWithInt:[[tempDic objectForKey:@"id"]intValue]*200], [NSNumber numberWithInt:[[tempDic valueForKey:@"id"] intValue]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"name"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"gender"]], [NSNumber numberWithInt:[[tempDic objectForKey:@"age"] intValue]], [NSNumber numberWithInt:(int)[tempDic objectForKey:@"weight"]], [NSNumber numberWithInt:[[tempDic objectForKey:@"tall"] intValue]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"qq"]], [NSString stringWithFormat:@"%@", [tempDic objectForKey:@"email"]], [NSNumber numberWithInt:[[tempDic objectForKey:@"phone"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneA"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneB"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneDr"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneA2"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneB2"] intValue]], [NSNumber numberWithInt:[[tempDic objectForKey:@"geneDr2"] intValue]], nil];
        NSLog(@"the inserted value in column 'idValue' is: %@" ,[tempDic objectForKey:@"id"]);
        [database close];

Спасибо за вашу помощь, я учусь каждый день благодаря сообществу stackOverflow.

person sebastien FCT    schedule 07.01.2014