如何使用NSMutableArray中的列名列表在sqlite3中创建表

时间:2012-12-11 12:19:56

标签: iphone objective-c ios sqlite sdk

我需要动态创建一个带有列的sqlite3表,实际上是存储在NSMutableArry中的列名,我想从NSMutableArrya值创建一个表。

3 个答案:

答案 0 :(得分:5)

试试这个:

- (void)viewDidLoad
  {
    NSString *idField = @"ID INTEGER PRIMARY KEY AUTOINCREMENT";
    NSString *nameField = @"NAME TEXT";
    NSString *ageField = @"AGE INTEGER";

   // Make the field array using different attributes in different cases
   NSArray *fieldArray = [NSArray arrayWithObjects:idField,nameField,ageField, nil];

     [self createTable:fieldArray];

   }

- (void)createTable:(NSArray *)fieldArray
  {
    // Put all the code for create table and just change the query as given below
    NSString *queryString = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS CONTACTS (%@)",[fieldArray componentsJoinedByString:@","]];
const char *sql_stmt = [queryString UTF8String];
  }

答案 1 :(得分:2)

您可以这样做,只需以正确的方式解析数组的数据

-(BOOL)createNewTable
{
    NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[array objectAtIndex:0];

filePath =[filePath stringByAppendingPathComponent:@"yourdatabase.db"];

NSFileManager *manager=[NSFileManager defaultManager];

BOOL success = NO;
if ([manager fileExistsAtPath:filePath]) 
{
    success =YES;
}
if (!success) 
{
    NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yourdatabase.db"];
    success =[manager copyItemAtPath:path2 toPath:filePath error:nil];
}
createStmt = nil;
NSString *tableName=@"SecondTable";
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
    if (createStmt == nil) {

        NSString *query=[NSString stringWithFormat:@"create table %@(rollNo integer, name text)",tableName];

        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) {
            return NO;
        }
        sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
        return YES;
    }
}

答案 2 :(得分:1)

要动态创建表,请使用以下创建查询:

NSString *query=[NSString stringWithFormat:@"create table '%@'('%@' integer, '%@' text)",yourTableName,[yourArray objectAtIndex:0],[yourArray objectAtIndex:1]];