4

我创建了一个应用程序。在我的应用程序中,我将 2 个数组存储在 sqlite 表数据库中,但我无法从 UItableView 中的 sqlite 显示。我在谷歌搜索,但没有找到关于从 sqlite 的故事板中显示数据的信息。!!!请指导我如何在 tableview 中显示来自 sqlite DB 的数据。这是我的代码:

#import "ViewController.h"
#define DataName @"DB.sqlite"

@implementation ViewController
{
    NSDictionary * dictionary;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *Name = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *Team = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        NSString * name = [Name objectAtIndex:i];
        NSString * team = [Team objectAtIndex:i];
        dictionary = [NSDictionary dictionaryWithObjectsAndKeys:name,@"Name",team,@"Team",nil];
        NSString *query = [NSString stringWithFormat:@"insert into tableFootball (Name,Team) values('%@','%@')",[dictionary objectForKey:@"Name"],[dictionary objectForKey:@"Team"]];
        [self executeQuery:query];
    }

}
-(NSString *) dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"PATH %@",[documentsDirectory stringByAppendingPathComponent:DataName]);
    return [documentsDirectory stringByAppendingPathComponent:DataName];
}
-(void)executeQuery:(NSString *)query
{
    //NSLog(@"QUERY : %@",query);

    sqlite3_stmt *statement;
    if(sqlite3_open([[self dataFilePath] UTF8String], &DataBase) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(DataBase, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) != SQLITE_DONE)
            {
                sqlite3_finalize(statement);
            }
        }
        else
        {
            NSLog(@"query Statement Not Compiled");
        }

        sqlite3_finalize(statement);
        sqlite3_close(DataBase);
    }
    else
    {
        NSLog(@"Data not Opened");
    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //I dont know what put here for display from sqlite
    return cell;
}
4

2 回答 2

4

创建一个方法,它将获取存储在 sqlite say 中的所有玩家findAllPlayers。创建一个 dataSourceArray 来保存从前一个方法返回的玩家。为了便于使用,可以很容易地形成模型自定义对象而不是字典。

//Player.h

@interface Player : NSObject

@property (nonatomic) NSUInteger playerID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *team;

一个实用程序 PlayerDatabase,它从 sqlite 插入和获取播放器实例。

//PlayerDatabase.h

@class Player;
@interface PlayersDatabase : NSObject

+ (PlayersDatabase*)database;
- (NSArray *)findAllPlayers;
- (BOOL)insertPlayer:(Player *)player;

//PlayerDatabase.m
@implementation PlayersDatabase

static PlayersDatabase *_database;

+ (PlayersDatabase*)database {
    if (_database == nil) {
        _database = [[PlayersDatabase alloc] init];
    }
    return _database;
}

- (id)init {
    if ((self = [super init])) {

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [self databasePath];
        if (![fileManager fileExistsAtPath:filePath]) {
            NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"Players"
                                                                 ofType:@"db"];
            [fileManager copyItemAtPath:sqLiteDb
                                 toPath:filePath
                                  error:NULL];
        }

    }
    return self;
}

- (NSString *)databasePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    return [documentsDirectory stringByAppendingPathComponent:@"Players.db"];
}

- (NSArray *)findAllPlayers
{
    NSMutableArray *players = [NSMutableArray array];
    FMDatabase *database = [FMDatabase databaseWithPath:[self databasePath]];
    [database open];

    FMResultSet *resultSet = [database executeQuery:@"SELECT * from Player ORDER BY Name"];

    while ([resultSet next]) {

        Player *player = [[Player alloc]init];

        player.playerID = [resultSet intForColumn:@"PlayerID"];
        player.name     = [resultSet stringForColumn:@"Name"];
        player.team     = [resultSet stringForColumn:@"Team"];

        [players addObject:player];

    }

    [database close];

    return players;
}

- (BOOL)insertPlayer:(Player *)player
{
     FMDatabase *db = [FMDatabase databaseWithPath:[self databasePath]];
     [db open];
     BOOL success =  [db executeUpdate:@"INSERT INTO Player (Name,Team) VALUES (?,?);",player.name,player.team, nil];
     [db close];
     return success;
}

现在在带有tableView的viewController中,首先填充sqlite然后重新加载tableView

//YourViewController.h 
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *names = [NSArray arrayWithObjects:@"Ribery",@"Ronaldo",@"Messi",@"Zannati",@"Totti", nil];
    NSArray *teams = [NSArray arrayWithObjects:@"byern",@"R.Madrid",@"Barcelona",@"Inter",@"Rome", nil];
    for (int i = 0; i < [Name count]; i++)
    {
        Player *player = [[Player alloc]init];

        player.name = names[i];
        player.team = teams[i];

        [[PlayerDatabase database] insertPlayer:player];
    }

    self.players = [self findAllPlayers];
    [self.tableView reloadData];

}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.players count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    //Here the dataSource array is of dictionary objects
    Player *player = self.players[indexPath.row];
    cell.textLabel.text = player.name;
    cell.detailTextLabel.text = player.team;

    return cell;
}

我按照上面提到的教程制定了一个示例项目,数据被预加载到 sqlite 中。因此,您可能需要对其进行调整以供使用。

源代码

于 2013-05-02T12:04:41.780 回答
0

从数据库sqlite中获取数据......你需要像这样写......并根据你的代码进行一些更改......

+(NSMutableArray*)getData
{
    NSString *strDestPath = [NSString stringWithFormat:@"%@/Documents/DBEmployee.sqlite",NSHomeDirectory()];
    sqlite3 *db;
    NSMutableArray   *empArr = [[NSMutableArray alloc]init];
    if(sqlite3_open([strDestPath UTF8String] , &db)  == SQLITE_OK)
    {
        NSString *query = @"SELECT * FROM Employee";
        char* err_msg;
        sqlite3_stmt* statement;
        if(sqlite3_prepare_v2(db, [query UTF8String], -1,&statement, &err_msg) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                DatabaseKeys *emp = [[DatabaseKeys alloc]init];
                emp.Eno = sqlite3_column_int(statement, 0);
                NSString *strn = [NSString stringWithFormat:@"%d",emp.Eno];
                [empArr addObject:strn];


            }
        }
    }
    return empArr;
}
于 2013-05-02T11:51:33.167 回答