Insert date to sqlite - iphone

I am making an iphone app in which there is use of database. In this database I am trying to save the date which is selected by using datepicker. But whenever I go to insert query it get crash and the error it shows i.e.
-[__NSDate UTF8String]: message sent to de allocated instance 0x5db1bf0.
I am unable to resolve this error. Please give me some solution to insert the date into the sqlite.
Thankyou very much.
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (btntagvalue == 2) {
if (buttonIndex != [actionSheet cancelButtonIndex]) {
selectedDate1 = [pickerView date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
frmdatestring = [formatter stringFromDate:selectedDate1];
newfromdate = [[NSDate alloc]init];
newfromdate = [[selectedDate1 addTimeInterval:-21600*4]copy];
NSLog(#"newdateis:%#",newfromdate);
fromdate.text = frmdatestring;
NSLog(#"proper date:%#",fromdate.text);
}
}
else if (btntagvalue == 3)
{
if (buttonIndex != [actionSheet cancelButtonIndex]) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
selectedDate2 = [pickerView1 date];
LastDate = selectedDate2;
todatestring = [formatter stringFromDate:selectedDate2];
todate.text = todatestring;
NSLog(#"proper date:%#",todate.text);
[self counteddays];
}
}
}
-(IBAction)savedetails:(id)sender
{
docname = doctname;
mail = email;
contactnum = contact;
medicname = mediname;
medictype = meditype;
Lastdatecolmn = (NSString*)LastDate;
[self insert1];
NSLog(#"docname:%#",docname);
NSLog(#"mail:%#",mail);
NSLog(#"contactnum:%#",contactnum);
NSLog(#"medicname:%#",medicname);
NSLog(#"medictype:%#",medictype);
for (int i =0; i<=[totaltimewithdate count]-1; i++) {
Dtime = [totaltimewithdate objectAtIndex:i];
[self insert];
}
[self docmedname];
}
-(void)insert
{
sqlite3_stmt *addStmt = nil;
if(addStmt == nil)
{
const char *sql = "insert into medicationdetail(doctorname, emailid, contactno,medicationname, medicationtype, datetime,LastDateColmn ) values (?,?,?,?,?,?,?)";
//NSLog(#"sq; %#", sql);
if(sqlite3_prepare_v2(database, sql , -1, &addStmt, NULL) != SQLITE_OK)
{
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [docname UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [mail UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [contactnum UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [medicname UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 5, [medictype UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 6, [Dtime UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 7, [Lastdatecolmn UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
{
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}

My guess would be that you're trying to create an NSDate attribute, but that you're mistakenly trying to set this as an NSString, e.g. #"01-01-1999".
If you check your "Date And Time Programming Guide" in your Apple Docs, you'll fine examples of how to create dates using date components.
Also have a look on Stack Overflow, where you'll quickly find plenty of examples if you search under "Create NSDate from NSString", e.g.:
get NSDate from NSString

Related

NULL data is inserted on the next index when original data is inserted

-(IBAction)btnAddToFavorite:(id)sender
{
[self insertDataToFavourites:[[tempDict objectForKey:#"pageid"]intValue]:[tempDict objectForKey:#"desc"]];
}
-(void)insertDataToFavourites:(int)pageid :(NSString *)description
{
sqlite3_stmt *insertStatement = nil;
NSString *sql;
int returnvalue;
sql = [NSString stringWithFormat:#"insert into AddFavorite (Id,Description) VALUES (?,?)"];
returnvalue = sqlite3_prepare_v2(database, [sql UTF8String], -1, &insertStatement, NULL);
NSLog(#"\nFavorite ID is:--> %d &\nDescription is:--> %#",[[tempDict valueForKey:#"pageid"] intValue] ,[tempDict valueForKey:#"desc"]);
if (returnvalue == 1){
NSAssert1 (0,#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_text(insertStatement, 1,[[tempDict objectForKey:#"pageid"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStatement, 2,[[tempDict objectForKey:#"desc"] UTF8String], -1, SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(insertStatement)){
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
else{
sqlite3_reset(insertStatement);
}
sqlite3_finalize(insertStatement);
}
This is a code to insert data into database. It is showing data like this, when i check database using select query.
Can anybody tell me where is the mistake ?
Thanks.
try to use the pageid method variable and not your dict, maybe the dict is wrong. On the other hand you insert for id
sqlite3_bind_text(insertStatement, 1,[[tempDict objectForKey:#"pageid"] UTF8String], -1, SQLITE_TRANSIENT);
i think this might be not correct.
For test case you can insert in SQLiteManager as sqlstatement
insert into AddFavorite (Id,Description) VALUES (1,'TestDescription');
to check if the statement is correct.
I would use this code to insert your values, if id is an int in your database
-(void)insertDataToFavourites:(int)pageid :(NSString *)description
{
sqlite3 *database;
if(sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "INSERT INTO AddFavorite (Id,Description) VALUES (?,?);";
sqlite3_stmt *compiled_statement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiled_statement, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiled_statement, 1, pageid);
sqlite3_bind_text(compiled_statement, 2, [description UTF8String] , -1, SQLITE_TRANSIENT);
}
if(sqlite3_step(compiled_statement) != SQLITE_DONE ) {
NSLog( #"Error: %s", sqlite3_errmsg(database) );
} else {
NSLog( #"Insert into row id = %lld", sqlite3_last_insert_rowid(database));
}
sqlite3_finalize(compiled_statement);
}
sqlite3_close(database);
}

Iinsert/Replace data in SQLite

Why can't I update data to SQLite eventhought it print "yes yes", please help, here my code, it called from viewdidload:
-(void)updateData{
CryptTestAppDelegate *delegate=(CryptTestAppDelegate *)[[UIApplication sharedApplication] delegate];
sqlite3_stmt *stmt=nil;
NSString *dd = #"testing";
const char *sql = "Update ProvPuzz set desc2=?";
sqlite3_prepare_v2(delegate.db, sql, 1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, [dd UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_step(stmt)){
NSLog(#"yes yes");
}else{
NSLog(#"no no");
}
sqlite3_finalize(stmt);
sqlite3_close(delegate.db);
}
It seems to pass every step, but my data not change at all. Any help please...
How should I call/code to be able to insert/replace these record in SQLite?
NSString *UpdateSql = [NSString stringWithFormat:#"Update ProvPuzz set desc2 = something"];
const char *sqlStatement = [UpdateSql UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(filesDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
if(sqlite3_step(compiledStatement) == SQLITE_DONE)
{
sqlite3_reset(compiledStatement);
}
}
// Release the compiled statement from memory
sqlite3_reset(compiledStatement);
sqlite3_finalize(compiledStatement);
sqlite3_close(filesDB);
and also check you db connection opened properly or not

How to store array value in sqlite in iphone

I'm getting error to store array value in database. My last array value is stored in database. I thought the counter was proper. Where in this code did I do wrong? I'm creating a counter in the database to store array values.
i got this error message Save Error: library routine called out of sequence
on this line ############
-(BOOL)Add
{
NSString *filePath = [BaseModal getDBPath];
NSLog(#"this check:%#",filePath);
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into Name(name,Date,CDate,Attach form,data) VALUES (?,?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString* date = [dateFormat stringFromDate:Date];
NSString* cdate = [dateFormat stringFromDate:Cdate];
sqlite3_bind_text( compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [date UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [cdate UTF8String], -1, SQLITE_TRANSIENT);
//sqlite3_bind_text( compiledStatement, 4, [UDate UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(compiledStatement, 4, Attach form);
sqlite3_bind_text( compiledStatement, 5, [data UTF8String], -1, SQLITE_TRANSIENT);
//sqlite3_bind_int(compiledStatement, 6, i);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database));
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
return FALSE;
}
else {
TaskId=sqlite3_last_insert_rowid(database);
sqlite3_reset(compiledStatement);
//sqlite3_finalize(compiledStatement);
//now insert into name table
const char *sqlStatement3 = "insert into TeaInfo(TitleId,TeaId) VALUES (?,?)";
sqlite3_stmt *compiledStatement3;
if(sqlite3_prepare_v2(database, sqlStatement3, -1, &compiledStatement3, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiledStatement3, 1, TitleId);
for(int counter=0;counter<[self.Tea count];counter++)//***************************
{
Teaclass *teaInfo=(Teaclass*)[self.Teas objectAtIndex:counter];
sqlite3_bind_int( compiledStatement3, 2, teaInfo. TeaId);
}
if(sqlite3_step(compiledStatement3) != SQLITE_DONE )//#############
{
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
//return FALSE;
}
//}
}
return TRUE;
}
}
return TRUE;
}
Solved problem in if(sqlite3_prepare_v2(database, sqlStatement3, -1, &compiledStatement3, NULL) == SQLITE_OK)this line I have to write in for loop then row is inserted properly.
Try the code below,
const char *sqlStatement3 = "insert into TeaInfo(TitleId,TeaId) VALUES (\"VALUE1\",\"VALUE2\)";

Memory optimization for sqlite requests - help needed

I'm using two methods to r/w sqlite table:
+ (NSString *) getWeatherData:(int)rowID:(int)columnID {
NSString *savedWeatherData = [[NSString alloc] init];
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from TABLE where id=?";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
sqlite3_bind_int(selectstmt, 1, rowID);
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Weather *weatherObj = [[Weather alloc] initWithPrimaryKey:primaryKey];
weatherObj.weatherData = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, columnID)];
savedWeatherData = weatherObj.weatherData;
[weatherObj release];
}
}
}
return [savedWeatherData autorelease];
}
And to save some data:
+ (void) saveDataToDataBase:(NSString *)columnToUpdate:(int)rowID:(NSString *)value {
if (sqlite3_open([[DBController getDBPath] UTF8String], &database) == SQLITE_OK) {
updateStmt = nil;
NSString *sqlString = [[#"update TABLE set " stringByAppendingString:columnToUpdate] stringByAppendingString:#"=? where id=?"];
const char *sql = [sqlString UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
} else { // select statement ok
sqlite3_bind_text(updateStmt, 1, [value UTF8String], -1, SQLITE_TRANSIENT); // replace first ? with value
sqlite3_bind_int(updateStmt, 2, rowID); // replace second ? with rowID
if(SQLITE_DONE != sqlite3_step(updateStmt)) {
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
} else {
// NSLog(#"Update completed !!!");
}
sqlite3_reset(updateStmt);
}
sqlite3_finalize(updateStmt);
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
With the Instruments, I see pretty big memory consumption for sqlite.
Info: during app startup, cca 100 different kind of data is stored in DB - for each data, this saveDataToDataBase method is called. (In case of no internet connection - getWeatherData would be used - and again cca 100 different kind of data would be read)
Please, can you instruct me - is it possible to optimize memory consumption.
Thanks a lot!
Kind regards!

inserting data in my sqlite database via iphone simulator

I am creating an iPhone application which makes use of sqlite database. I have one table in my database. Initially there are no rows in my table. I want that when I insert a new record via my iPhone simulator that record should be automatically updated to my database. How Could this be possible. Please anybody help me in solving this problem.
+ (void) getInitialDataToDisplay:(NSString *)dbPath
{
SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select coffeeID, coffeeName from coffee";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.coffeeName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
coffeeObj.isDirty = NO;
[appDelegate.coffeeArray addObject:coffeeObj];
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
+ (void) finalizeStatements
{
if (database) sqlite3_close(database);
if (deleteStmt) sqlite3_finalize(deleteStmt);
if (addStmt) sqlite3_finalize(addStmt);
if (detailStmt) sqlite3_finalize(detailStmt);
if (updateStmt) sqlite3_finalize(updateStmt);
}
- (id) initWithPrimaryKey:(NSInteger) pk
{
[super init];
coffeeID = pk;
coffeeImage = [[UIImage alloc] init];
isDetailViewHydrated = NO;
return self;
}
- (void) deleteCoffee
{
if(deleteStmt == nil) {
const char *sql = "delete from Coffee where coffeeID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
}
//When binding parameters, index starts from 1 and not zero.
sqlite3_bind_int(deleteStmt, 1, coffeeID);
if (SQLITE_DONE != sqlite3_step(deleteStmt))
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(database));
sqlite3_reset(deleteStmt);
}
- (void) addCoffee
{
if(addStmt == nil) {
const char *sql = "insert into Coffee(CoffeeName, Price) Values(?, ?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_double(addStmt, 2, [price doubleValue]);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
coffeeID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
- (void) hydrateDetailViewData
{
//If the detail view is hydrated then do not get it from the database.
if(isDetailViewHydrated) return;
if(detailStmt == nil) {
const char *sql = "Select price, CoffeeImage from Coffee Where CoffeeID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating detail view statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_int(detailStmt, 1, coffeeID);
if(SQLITE_DONE != sqlite3_step(detailStmt)) {
//Get the price in a temporary variable.
NSDecimalNumber *priceDN = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(detailStmt, 0)];
//Assign the price. The price value will be copied, since the property is declared with "copy" attribute.
self.price = priceDN;
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(detailStmt, 1) length:sqlite3_column_bytes(detailStmt, 1)];
if(data == nil)
NSLog(#"No image found.");
else
self.coffeeImage = [UIImage imageWithData:data];
//Release the temporary variable. Since we created it using alloc, we have own it.
[priceDN release];
}
else
NSAssert1(0, #"Error while getting the price of coffee. '%s'", sqlite3_errmsg(database));
//Reset the detail statement.
sqlite3_reset(detailStmt);
//Set isDetailViewHydrated as YES, so we do not get it again from the database.
isDetailViewHydrated = YES;
}
- (void) saveAllData
{
if(isDirty)
{
if(updateStmt == nil)
{
const char *sql = "update Coffee Set CoffeeName = ?, Price = ?, CoffeeImage = ? Where CoffeeID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(updateStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_double(updateStmt, 2, [price doubleValue]);
NSData *imgData = UIImagePNGRepresentation(self.coffeeImage);
int returnValue = -1;
if(self.coffeeImage != nil)
returnValue = sqlite3_bind_blob(updateStmt, 3, [imgData bytes], [imgData length], NULL);
else
returnValue = sqlite3_bind_blob(updateStmt, 3, nil, -1, NULL);
sqlite3_bind_int(updateStmt, 4, coffeeID);
if(returnValue != SQLITE_OK)
NSLog(#"Not OK!!!");
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(updateStmt);
isDirty = NO;
}
//Reclaim all memory here.
[coffeeName release];
coffeeName = nil;
[price release];
price = nil;
isDetailViewHydrated = NO;
}
- (void)setCoffeeName:(NSString *)newValue
{
self.isDirty = YES;
[coffeeName release];
coffeeName = [newValue copy];
}
- (void)setPrice:(NSDecimalNumber *)newNumber
{
self.isDirty = YES;
[price release];
price = [newNumber copy];
}
- (void)setCoffeeImage:(UIImage *)theCoffeeImage
{
self.isDirty = YES;
[coffeeImage release];
coffeeImage = [theCoffeeImage retain];
}
Well, as I see you have this function +(void) finalizeStatements; where you close your DB and finalize your prepared queries.
First of all, you don't call this function from anywhere. Anyway if you are somehow calling this function, the code from is not correct, because you should first finalize all statements and only after that close the connection.
Read the documentation of sqlite3_close and sqlite3_finalize. What the documentation says about sqlite3_close:
Applications must [sqlite3_finalize | finalize] all [prepared statements] and [sqlite3_blob_close | close] all [BLOB handles] associated with the [sqlite3] object prior to attempting to close the object.
If that won't help you, try to finalize statements at the end of each method you prepare it.
Hope this helps you.
I'm not sure the database variable you've opened in getInitialDataToDisplay is still available when you try to addCoffee. Why don't you close that connection, and open a new one at the beginning of addCoffee (and close that when it completes)