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.
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];
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With