我从sqlite的xcode中获取表中的数据,我想在数组中只插入id列

时间:2014-09-22 11:47:50

标签: ios xcode sqlite

NSString *query = @"select id from info";
     // Get the results.
    if (self.arrPeopleInfo != nil) {
        self.arrPeopleInfo = nil;
    }
    self.arrPeopleInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];

    // Reload the table view.
    //[self.tblPeople reloadData];

    /*_maintitle = @[@"Title 1",
                   @"Title 2",
                   @"Title 3",
                   @"Title 4",
                   @"Title 5",
                   @"Title 6",
                   @"Title 7"];*/
    NSArray *allval = _arrPeopleInfo;

    NSLog(@"%@", allval);

在上面的代码中,我想把所有的id从数据库中取出,然后像所有id一样创建像_maintitle这样的数组。

1 个答案:

答案 0 :(得分:0)

你应该真正将标题存储在数据库中,并且允许最大的灵活性和一致性(在某些数据库上,除了sqlite之外,数据库引擎可以通过检查info.id列来确保它是有效的针对titles表格:

CREATE TABLE titles (
    id INTEGER PRIMARY KEY,
    title TEXT
);

INSERT INTO titles (id, title) VALUES (1, 'Title 1');
INSERT INTO titles (id, title) VALUES (2, 'Title 2');
INSERT INTO titles (id, title) VALUES (3, 'Title 3');
INSERT INTO titles (id, title) VALUES (4, 'Title 4');
INSERT INTO titles (id, title) VALUES (5, 'Title 5');
INSERT INTO titles (id, title) VALUES (6, 'Title 6');
INSERT INTO titles (id, title) VALUES (7, 'Title 7');
INSERT INTO titles (id, title) VALUES (8, 'Title 8');

然后你可以一举选择id和title

SELECT i.id, t.title
FROM info i, titles t
WHERE t.id = i.id
ORDER BY i.id ASC;

请勿忘记ORDER BY条款,因为您需要在整个应用有效期内保持一致的排序。

您发布的代码也是次优的:

NSString *query = @"<the statement above>";
self.arrPeopleInfo = [self.dbManager loadDataFromDB:query];