tags:

views:

42

answers:

3

Hi guys. i have a database that is in the documents directorys of the Application/iPhoneSimulator/3.2/Applications/etc/Documents

I have this code under my method

    databaseName = @"database.sql";
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory.NSUserDomainMask,YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

How do i do an insert with a variable/ array . Something like "INSERT INTO TABLE (COLUMN) VALUES ('%@'),[appDelegate.variable objectAtIndex:0];

+1  A: 
+(NSString *)stringWithFormat:(NSString *)format parameters:...];

NSString sql = [NSString stringWithFormat:@"INSERT INTO table VALUES('%@')", @"Hello, world!"];
sqlite3_....
Nick Bedford
This wouldn't work with e.g. `@"foo 'bar'"` et al.
Georg Fritzsche
In that case you would want to escape your single-quotes by replacing them with double single-quotes.
Nick Bedford
+1  A: 

Use either prepared statements in combination with the bind_*() functions (e.g. bind_text()) or the mprintf() function to insert strings, see this question for details.

To get a raw C-string you can pass to these functions use -UTF8String or -cStringUsingEncoding: on a NSString.

Georg Fritzsche
+1  A: 

I insist you to go through this question. First of all copy the database from main bundle to your application's document dir. You can follow below code to implement it.

    NSString *databaseFile=[[NSBundle mainBundle] pathForResource:kDataBaseName ofType:kDataBaseExt];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *dbPath=[basePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",kDataBaseName,kDataBaseExt]];
    NSFileManager *fm=[NSFileManager defaultManager];

    if(![fm fileExistsAtPath:dbPath]){
        [fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
    }

    [fm release];

    self.dataBasePath=dbPath;

I am supplying you directly my project code. Please add comment if any doubts. I have added comments for the explanation.

// function with multiple arguments which is going to be used for inserting into table.
+(void)insertBuilding:(NSString*)BName streetNo:(NSInteger)streetNo streetName:(NSString*)streetName streetDir:(NSString*)streetDir muni:(NSString*)muni province:(NSString*)province bAccess:(NSString*)bAccess bType:(NSString*)bType amnity:(NSString*)amnity latitude:(NSString*)latitude longitude:(NSString*)longitude imageName:(NSString*)imageName {
    // application delegate where I have saved my database path.
    BuildingLocatorAppDelegate *x=(BuildingLocatorAppDelegate *)[[UIApplication sharedApplication]delegate];
    sqlite3 *database; // database pointer
    // verifying if database successfully opened from path or not.
    // you must open database for executing insert query    
    // i have supplied database path in argument 
    // opened database address will be assigned to database pointer.
    if(sqlite3_open([[x dataBasePath] UTF8String],&database) == SQLITE_OK) {
        // creating a simple insert query string with arguments.
        NSString *str=[NSString stringWithFormat:@"insert into buildingDtl(b_name,streetNo,streetName,streetDir,muni,province,b_access,b_type,aminity,latitude,longitude,b_image) values('%@',%i,'%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",BName,streetNo,streetName,streetDir,muni,province,bAccess,bType,amnity,latitude,longitude,imageName];
        // converting query to UTF8string.
        const char *sqlStmt=[str UTF8String];       
        sqlite3_stmt *cmp_sqlStmt;
        // preparing for execution of statement.
        if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK) {
            int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);
            ((returnValue==SQLITE_OK) ?  NSLog(@"Success") :  NSLog(@"UnSuccess") );
                // if NSLog -> unsuccess - that means - there is some problem with insert query.
            sqlite3_step(cmp_sqlStmt);
        }
        sqlite3_finalize(cmp_sqlStmt);
    }
    sqlite3_close(database);
    // please don't forget to close database.
}
sugar
Hi i tried this and had a success in the NSLOG. But however when i try to read the database again, the values werent there
Kenneth
Kenneth
// Setup the SQL Statement and compile it for faster access const char *sqlStatement = "Select EntryID From XMLEntryID ORDER BY xeID DESC LIMIT 1 "; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement,-1,
Kenneth
// Add the user object to the users Array and respectively [appDelegate.dBCount addObject:aEntryID]; view = [[UIAlertView alloc] initWithTitle: @"A Message" message: aEntryID delegate: self cancelButtonTitle: @"Yay.!" otherButtonTitles: nil]; [view show]; [view autorelease]; [aEntryID release]; return; } } // Release the compiled statement from memory sqlite3_finalize(compiledStatement); } sqlite3_close(database);
Kenneth
this is the code in my method to read the database for the latest value that i have, however it seems that the values weren't inserted .
Kenneth
sugar
sugar
have you placed code for copying the database from main bundle to documents directory - or just pasted directly above code ?
sugar
iv check every database in my pc and there werent any new data , below is the code for the inserting
Kenneth
//setup some globals databaseName = @"MedicalBedDatabase.sql"; //Get the path to the documents NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
Kenneth
please see edited answer :)
sugar
sqlite3 *database; if(sqlite3_open([databasePath UTF8String], const char *sqlStmt = [str UTF8String]; sqlite3_stmt *cmp_sqlStmt; if(sqlite3_prepare_v2(database, sqlStmt, -1, ((returnValue ==SQLITE_OK) ? NSLog(@"INSERT SUCCESS") : NSLog(@" INSERT Fail")); sqlite3_step(cmp_sqlStmt); }
Kenneth
sqlite3_finalize(cmp_sqlStmt); } sqlite3_close(database);
Kenneth
where do i implement that? in the appDelegate.m?
Kenneth
Ahhh :p it's up to your requirement. It's up to what you prefer. I prefer to place it on appDelegate.m - so, I placed there. Choice is up to you - where you save the database path string.
sugar
hmm i think im having the correct database path. However i tried inserting values into the table on the Terminal applications but returns meSQL error: unable to open database file. Is it possible that the file is read-only? If so how can i change it
Kenneth
*UPDATE*It works! i found out i was doign something silly in my method that caused the database to be locked
Kenneth