Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create table in sqlite3 with a list of column name in NSMutableArray

I need to create a sqlite3 table with column dynamically , actually the column names stored in NSMutableArry , i want to create a table from NSMutableArrya Values.

like image 644
user1523184 Avatar asked Dec 03 '25 17:12

user1523184


2 Answers

Try this :

- (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];
  }
like image 143
Anusha Kottiyal Avatar answered Dec 06 '25 07:12

Anusha Kottiyal


You can do it in such a way, just parse the data of you array the right way

-(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;
    }
}
like image 27
Dmitry Zheshinsky Avatar answered Dec 06 '25 08:12

Dmitry Zheshinsky