如何在表格视图中显示数据库的数据

时间:2017-05-03 05:03:48

标签: objective-c sqlite

您好我是sqlite数据库的新手,我想在tableview中点击(显示数据按钮),在第二个视图控制器中显示我存储在数据库中的数据。

以下是我的数据库代码

文件DBManager.h

@interface DBManager : NSObject
{
    NSString *databasePath;
}

+(DBManager*)getSharedInstance;

-(BOOL)createDB;
-(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
      department:(NSString*)department year:(NSString*)year;
-(NSArray*) findByRegisterNumber:(NSString*)registerNumber;

@end

文件DBManager.m

static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;

@implementation DBManager

+(DBManager *)getSharedInstance
{
    if (!sharedInstance) {
        sharedInstance = [[super allocWithZone:NULL]init];
        [sharedInstance createDB];
    }

    return sharedInstance;
}

-(BOOL)createDB
{
    NSString *docsDir;
    NSArray *dirPaths;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    NSLog(@"%@", docsDir);

    databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"student.db"]];

    BOOL isSuccess = YES;
    NSFileManager *filemngr = [NSFileManager defaultManager];
    if ([filemngr fileExistsAtPath:databasePath] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            char *errMsg;
            const char * sql_stmt = "create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";

            if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK)
            {
                isSuccess = NO;
                NSLog(@"Failed to create table");
            }

            sqlite3_close(database);
            return isSuccess;
        }
        else
        {
            isSuccess = NO;
            NSLog(@"Failed to open/create database");
        }
    }
    return  isSuccess;
}

-(BOOL)saveData:(NSString *)registerNumber name:(NSString *)name department:(NSString *)department year:(NSString *)year;
{
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat:@"insert into studentsDetail (regno,name,department,year) values (\"%ld\",\"%@\",\"%@\",\"%@\")",(long)[registerNumber integerValue],name,department,year];

        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);

        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            return YES;
        }
        else
        {
            return NO;
        }
        //sqlite3_reset(statement);
    }
    return NO;
}

- (NSArray*) findByRegisterNumber:(NSString*)registerNumber
{
    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:@"select name,department,year from studentsDetail where regno=\"%@\"",registerNumber];
        const char *query_stmt = [querySQL UTF8String];
        NSMutableArray *resultArray = [[NSMutableArray alloc]init];
        if (sqlite3_prepare_v2(database,
                               query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            if (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *name = [[NSString alloc] initWithUTF8String:
                                  (const char *) sqlite3_column_text(statement, 0)];
                [resultArray addObject:name];
                NSString *department = [[NSString alloc] initWithUTF8String:
                                        (const char *) sqlite3_column_text(statement, 1)];
                [resultArray addObject:department];
                NSString *year = [[NSString alloc]initWithUTF8String:
                                  (const char *) sqlite3_column_text(statement, 2)];
                [resultArray addObject:year];
                NSLog(@"%@", resultArray);
                return resultArray;
            }
            else{
                NSLog(@"Not found");
                return nil;
            }
            //sqlite3_reset(statement);
        }
    }
    return nil;
}
@end

请帮帮我..

1 个答案:

答案 0 :(得分:0)

更新代码:

<强> DBManager.m

-(NSArray *) showdata{

  const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM  studentsDetail"];

    const char *query_stmt = [querySQL UTF8String];

    NSMutableArray *resultentArray=[[NSMutableArray alloc]init];

    if (sqlite3_prepare_v2(database,
                           query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {

            NSMutableDictionary *resultentDict = [[NSMutableDictionary alloc] init];

            NSString *name = [[NSString alloc] initWithUTF8String:
                              (const char *) sqlite3_column_text(statement, 0)];

            NSString * department = [[NSString alloc] initWithUTF8String:
                                     (const char *) sqlite3_column_text(statement, 1)];
            NSString *year = [[NSString alloc] initWithUTF8String:
                              (const char *) sqlite3_column_text(statement, 2)];

            NSLog(@"%@",resultentDict);

            [resultentDict setValue:name forKey:@"name"];

            [resultentDict setValue:department forKey:@"department"];
              [resultentDict setValue:year forKey:@"year"];

            NSLog(@"%@",resultentDict);
            NSLog(@"%@",resultentArray);

            [resultentArray addObject:resultentDict];
            NSLog(@"%@",resultentArray);


        }

        return resultentArray;
    }
    sqlite3_close(database);

}
return nil;
}

之后我创建了一个名为show data的按钮...如果我点击它会导航到另一个TableViewController:

我这样实施

TableViewController中的

   - (void)viewDidLoad {
      [self showData];

    }

    -(void)showData{

        data = [[DBManager getSharedInstance]showdata];
        NSLog(@"DATA %@",data);

        NSLog(@"%lu",(unsigned long)[[data valueForKey:@"price"] count]);


    }



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[data valueForKey:@"price"] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    NSLog(@"%@",data);
//    cell.textLabel.text = [[data valueForKey:@"year"]objectForKey:indexPath.row];

    cell.textLabel.text=[[data valueForKey:@"price"]objectAtIndex:indexPath.row];
    return cell;
}