0

我有四列的 SQLite 数据库

例子 :

id 姓名 电子邮件 手机
------------------------------------------
1 Vishal V@gmail.com 5654485
2 拉瓦尔 R@gmail.com 5544555
3 VVV 55555
4 RRRR                             
5 TTTT T@gmail 5555

我想要特定数组中的特定列值。

例如 :

  • 在 NameArray 我想要存储在数据库名称列中的所有值
  • 在 EmailArray 我想要存储在数据库的电子邮件列中的所有值
4

3 回答 3

1

简短的回答是,您只需实例化您的数组,遍历 SQLite 结果,将对象添加到您的数组中。

长答案:

  1. 我同意 trojanfoe 的观点,即您应该为表的四列维护单独的数组。您应该有一个单独的类,例如Contact,它包含所有四个列值,然后构建一个数组。因此,该类可能如下所示:

    @interface Contact : NSObject
    
    @property (nonatomic) long long contactId;
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, copy) NSString *email;
    @property (nonatomic, copy) NSString *mobile;
    
    @end
    
    @implementation Contact
    
    // nothing required here
    
    @end
    
  2. 你说你正在使用 SQLite。我建议您考虑使用FMDB。这是一个围绕SQLite C 语言 API的精简包装器,极大地简化了您与 SQLite 数据库的交互。我下面的示例将使用这个 FMDB 库。

  3. 因此,正如“简短答案”中所建议的,您只需遍历 SQL 结果,将项目添加到数组中:

    FMDatabase *database = [FMDatabase databaseWithPath:path];
    BOOL success = [database open];
    NSAssert(success, @"database open failed");
    
    FMResultSet *rs = [database executeQuery:@"select id, name, email, mobile from test"];
    NSAssert(rs, @"select failed: %@", [database lastErrorMessage]);
    
    NSMutableArray *contacts = [NSMutableArray array];
    
    while ([rs next])
    {
        Contact *contact = [[Contact alloc] init];
        contact.contactId = [rs longLongIntForColumn:@"id"];
    
        id name = rs[@"name"];
        if (name != [NSNull null])       // if the column can be NULL, you might want to check for that condition
            contact.name = name;
    
        id email = rs[@"email"];
        if (email != [NSNull null])
            contact.email = email;
    
        id mobile = rs[@"mobile"];
        if (mobile != [NSNull null])
            contact.mobile = mobile;
    
        [contacts addObject:contact];
    }
    
    [rs close];
    
  4. 现在,您可以像这样访问该contacts数组中的信息:

    Contact *contact = contacts[2];
    NSString *email = contact.email;
    

    第一行检索对第三个联系人的引用。下一行检索该联系人的电子邮件地址。希望这能说明这个想法。

显然,如果您决定使用 SQLite C 语言接口(例如,调用sqlite3_opensqlite3_prepare_v2等),您可以,但它需要更多的工作(尤其是当您开始使用 SQL 语句的参数时)。我强烈推荐使用 FMDB。

同样,如果您想为表格的四列设置单独的数组,您可以这样做,但是使用像上述Contact类这样的类要优雅得多,并且会产生更多逻辑代码。

于 2013-10-03T14:08:57.060 回答
0

您需要先执行 fetch 请求,如下所示:

NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
    entityForName:yourTable inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];

参考这个:https ://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html

然后,您需要执行以下操作:

NSArray *names = [array valueForKeyPath:@"@unionOfObjects.Name"];

参考:https ://developer.apple.com/library/mac/documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html

于 2013-10-03T13:22:59.007 回答
0

有很多事情要做:

  1. 将数据库放在应用程序中
  2. 导入库 sqlite3
  3. 创建两个文件作为 NSObject 的子类(调用数据库)
  4. 导入database.h

现在要在 database.h 中编写代码:

@interface 数据库:NSObject {

NSString *databaseName;   
NSString *databasePath;

 }
 @property(nonatomic,retain)NSString *databaseName; 
 @property(nonatomic,retain)NSString *databasePath;

-(void)startDB;
-(void)checkAndCreateDatabase;

现在.m:

@implementation database : NSObject
@synthesize databasePath, databaseName;

-(void)startDB {

   // Setup some globals
   databaseName = @"yourdb.sqlite";

  // Get the path to the documents directory and append the databaseName
  NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDir = [documentPaths objectAtIndex:0];
  databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

  // Execute the "checkAndCreateDatabase" function
   [self checkAndCreateDatabase];

}


 -(void)checkAndCreateDatabase{
 // Check if the SQL database has already been saved to the users phone, if not then copy it over
 BOOL success;

 // Create a FileManager object, we will use this to check the status
 // of the database and to copy it over if required
 NSFileManager *fileManager = [NSFileManager defaultManager];

 // Check if the database has already been created in the users filesystem
 success = [fileManager fileExistsAtPath:databasePath];

 // If the database already exists then return without doing anything
 if(success) return;

 // If not then proceed to copy the database from the application to the users filesystem

 // Get the path to the database in the application package
 NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

 // Copy the database from the package to the users filesystem
 [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];


}

用表的特定列填充数组:

在 ViewController.m 中导入 database.h 并编写以下代码:

-(void)viewWillAppear:(BOOL)animated {

 [self queryNomi];

}


-(void)queryNomi {

[arrayName removeAllObjects];
[arrayEmail removeAllObjects];

database *dbDelegate = [[database alloc]init];

[dbDelegate startDB];

sqlite3 *database;

NSString *queryName = [NSString stringWithFormat:@"SELECT Name FROM nameTable"];
NSString *queryEmail = [NSString stringWithFormat:@"SELECT Email FROM nameTable"];


if(sqlite3_open([dbDelegate.databasePath UTF8String], &database) == SQLITE_OK) {


    sqlite3_stmt *compiledStatement1;
    sqlite3_stmt *compiledStatement2;


    if(sqlite3_prepare_v2(database, [queryName UTF8String], -1, &compiledStatement1, NULL) == SQLITE_OK) {

        while(sqlite3_step(compiledStatement1) == SQLITE_ROW) {
            [arrayName addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement1, 0)]];

        }

    }

    if(sqlite3_prepare_v2(database, [queryEmail UTF8String], -1, &compiledStatement2, NULL) == SQLITE_OK) {

        while(sqlite3_step(compiledStatement2) == SQLITE_ROW) {
            [arrayEmail addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement2, 0)]];
        }

    }


    sqlite3_finalize(compiledStatement1);
    sqlite3_finalize(compiledStatement2);
    sqlite3_close(database);
}


 //    [self.tableView reloadData];
}

我似乎都写了..让我知道!

于 2013-10-03T20:39:54.763 回答