8

hai i a'm trying to create a sqlite database programmatically at the run time. can anybody say how to create it in iphone sdk.

3 Answers 3

20

Just call the sqlite3_open function it will create a database if no database exist on the path.

// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
{

// your  code here
}

post a comment if you need more code example on this

Sign up to request clarification or add additional context in comments.

1 Comment

any tutorials on this topic, saurabh. Please can u give us thanks you
3
-(void)viewDidLoad
{
    [super viewDidLoad];
    NSString *docsDir;
    NSArray *dirPaths;
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];
    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
    const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"if");

            }

            sqlite3_close(contactDB);

        } else 
        {
            NSLog(@"else");

        }
    }
    [filemgr release];

}

-(IBAction)table
{
    NSString *docsDir;
    NSArray *dirPaths;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

   // if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {

                  NSLog(@"tables failed");
               // status.text = @"Failed to create table";
            }

            sqlite3_close(contactDB);

        }
        else 
        {

            NSLog(@"tables failed");
            //status.text = @"Failed to open/create database";

        }
    }

    [filemgr release];
}  

1 Comment

import in .m file #import<sqlite3.h> and add framework in ur project libsqlite3.0.dylib....thanks:)
2

import in .m file #import sqlite3.h and add framework in ur project libsqlite3.0.dylib

firstly create NSObject class and named it Database. in .h class

  @interface database : NSObject

   {
    NSString *databasePath;
NSString *databaseName;
sqlite3 *myDatabase;
NSArray *documentPaths;
NSString *documentsDir;  

}

//---initial methods-------

 -(void)createDatabaseIfNeeded;

//-----------------path find method---------------------//

  -(void)pathFind;

//-----------------write value----------------------//

  -(void)writeValueInSettings:(NSMutableArray *)arrayvalue;

//-------------------fetch value from setting table------------//

    -(NSMutableArray *)fetchValue;

//-------------------update value---------------------//

    -(void)updateSetting:(NSArray *)arr;

.m class write

 -(id)init
  {
if((self=[super init]))
{
    [self createDatabaseIfNeeded];
}
return self;    
  }

 //-----------create database if needed method--------------//
 -(void)createDatabaseIfNeeded
  {
[self pathFind];

BOOL success;
NSFileManager *filemgr = [NSFileManager defaultManager];
success=[filemgr fileExistsAtPath:databasePath];

if (success)return;

NSLog(@"not success");

//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
[filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];


    }

//----------------path find-----------------//

  -(void)pathFind
    {
databaseName = @"accDataBase.DB";
// Get the path to the documents directory and append the databaseName
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
  }

//------------------write value in setting----------------//

  -(void)writeValueInSettings:(NSMutableArray *)arrayvalue
   {   
   NSLog(@"%@",arrayvalue);

   if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)

  {
    database *objectDatabase=[[database alloc]init];

    NSString *stringvalue2=[objectDatabase countValue];
    [objectDatabase release];
    int intvalue1=[stringvalue2 intValue];

    intvalue1=intvalue1+1;
    NSLog(@"opened");
    NSString *sql1;

    sql1=[[NSString alloc] initWithFormat:@"insert into setting values('%i','%i','%i','%@','%i','%i','%@','%i','%i','%i','%i','%i','%i','%@');",intvalue1,
          [[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
    char *err1;
    if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
    {
        NSLog(@"value inserted:");
    }
    [sql1 release];
    sqlite3_close(myDatabase);
}

} //------------fetch all value-------------//

   -(NSMutableArray *)fetchValue
    {
NSMutableArray *list=nil;

    list=[[[NSMutableArray alloc]init] autorelease];

if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{

    NSString *sql=[NSString stringWithFormat: @"select * from setting where primaryKey=1"];
          sqlite3_stmt *statement;

    if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
    {
        if(sqlite3_step(statement)==SQLITE_ROW)
        {
            for(int i=0;i<=13;i++)
            {
                char *pass=(char*)sqlite3_column_text(statement,i);
                NSString *msg=[[NSString alloc]initWithUTF8String:pass];
                [list addObject:msg];
                [msg release];
            }

        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(myDatabase);
   }

  return list;

      }

//----------------update setting table method---------------//

    -(void)updateSetting:(NSArray *)arr
    {    
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
    NSLog(@"opened");
    sqlite3_stmt *compiledStmt;

   // NSLog(@"%@",arr);

    NSString *sqlStmt=[NSString stringWithFormat:@"UPDATE setting SET ragular=%i,cycle=%i, flow='%@', hour=%i,minute=%i,formate='%@' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%@',formatemessage ='%@' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
 //   NSLog(@"%@",sqlStmt);
     if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK) 
      {
    NSLog(@"updateding......cycle");
        }
    sqlite3_step(compiledStmt);
    sqlite3_close(myDatabase);
}

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.