3

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

4

3 回答 3

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];
  }
于 2012-12-11T12:26:45.463 回答
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;
    }
}
于 2012-12-11T12:23:46.087 回答
1

要动态创建表,请使用 create 查询,例如:

NSString *query=[NSString stringWithFormat:@"create table '%@'('%@' integer, '%@' text)",yourTableName,[yourArray objectAtIndex:0],[yourArray objectAtIndex:1]];
于 2012-12-11T12:26:01.000 回答