SLQLite 'Error while updating. 'constraint failed'' - iphone

Been Trying for 8 hours, not too sure which part gone wrong. i know is the ID problem as i tried the last record. it is supposed to be ID 5, but the NSlog shows 6 instead.
i removed all the unique id, so is not reserve key problem.
thanks for looking.
Please help, i going crazy........
- (id) initWithPrimaryKey:(NSInteger)pk
{
self = [super init];
ID = pk;
isDetailViewHydrated = NO;
return self;
}
- (void)saveAllData
{
if(isDirty) {
if(updateStmt == nil) {
const char *sql = "UPDATE identifyF SET TypeName = ?, gDate = ?, Location = ?, GeoCode = ?,Note = ?, Image = ?, TypeID = ? WHERE ID = ?";
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(addStmt, 1, [TypeName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [DateStr UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3, [Location UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 4, [GeoCode UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 5, [Note UTF8String], -1, SQLITE_TRANSIENT);
//image
NSData *imgData = UIImagePNGRepresentation(self.Image);
int returnValue = -1;
if(self.Image != nil)
returnValue = sqlite3_bind_blob(updateStmt, 6, [imgData bytes], [imgData length], NULL);
else
returnValue = sqlite3_bind_blob(updateStmt, 6, nil, -1, NULL);
sqlite3_bind_text(updateStmt, 7, [TypeID UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt, 8, ID);;
NSLog(#"frog name %#",TypeName);
NSLog(#"frog date %#",DateStr);
NSLog(#"location %#",Location);
NSLog(#"Geo code %#",GeoCode);
NSLog(#"note %#",Note);
NSLog(#"Img %#",Image);
NSLog(#"Type ID %#",TypeID);
NSLog(#"Frog ID %d",ID);
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;
}
isDetailViewHydrated = NO;
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath
{
FinderAppDelegate * appDelegate = (FinderAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.idArray removeAllObjects];
//identifyArray = [[NSMutableArray alloc] init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "SELECT ID,TypeID,TypeName,Date,Location,GeoCode,Note,Image FROM identify";
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);
identify *my = [[identify alloc] initWithPrimaryKey:primaryKey];
// my.TypeID = sqlite3_column_int(selectstmt, 1);
my.TypeID = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt,1)];
my.TypeName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt,2)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString *dateStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
my.Date = [formatter dateFromString:dateStr];//[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
my.Location = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt, 4)];
my.GeoCode = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt, 5)];
my.Note = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt, 6)];
const char *raw = sqlite3_column_blob(selectstmt, 7);
int rawLen = sqlite3_column_bytes(selectstmt, 7);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
my.Image = [[UIImage alloc] initWithData:data];
my.isDirty = NO;
[appDelegate.idArray addObject:my];
}
}
} else sqlite3_close(database); //close db to release all memory
}
*** Assertion failure in -[identify saveAllData], /Users/Desmond/Desktop/Finder desmond new design 2/Finder/identify.m:241
Current language: auto; currently objective-c
Catchpoint 2 (exception thrown).objc[58781]: EXCEPTIONS: throwing 0x130db720 (object 0x1418bab0, a NSException)
objc[58781]: EXCEPTIONS: searching through frame [ip=0x1cb3db3 sp=0xbffff4c0] for exception 0x130db700
objc[58781]: EXCEPTIONS: unwinding through frame [ip=0x1cb3db3 sp=0xbffff4c0] for exception 0x130db700
objc[58781]: EXCEPTIONS: handling exception 0x130db700 at 0x1cb3e46
objc[58781]: EXCEPTIONS: rethrowing current exception
objc[58781]: EXCEPTIONS: searching through frame [ip=0x1cb3e0f sp=0xbffff4c0] for exception 0x130db700
objc[58781]: EXCEPTIONS: terminating
objc[58781]: EXCEPTIONS: searching through frame [ip=0x1f0ef21 sp=0xbffff450] for exception 0x130db700
objc[58781]: EXCEPTIONS: catch(id)
objc[58781]: EXCEPTIONS: unwinding through frame [ip=0x1f0ef21 sp=0xbffff450] for exception 0x130db700
objc[58781]: EXCEPTIONS: handling exception 0x130db700 at 0x1f0ef33
2012-01-15 22:58:07.006 FrogFinder[58781:15b03] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error while updating. 'constraint failed''
*** First throw call stack:
(0x1d7d052 0x1f0ed0a 0x1d25a78 0x132c2db 0x93167 0x952c9 0x1d7eec9 0x9a65c2 0xbe1d54 0x1d7eec9 0x9a65c2 0x9a655a 0xa4bb76 0xa4c03f 0xa4b2fe 0x9cba30 0x9cbc56 0x9b2384 0x9a5aa9 0x27a1fa9 0x1d511c5 0x1cb6022 0x1cb490a 0x1cb3db4 0x1cb3ccb 0x27a0879 0x27a093e 0x9a3a9b 0x1f3a 0x1ed5)

sqlite3_bind_text(addStmt, 1, [TypeName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [DateStr UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3, [Location UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 4, [GeoCode UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 5, [Note UTF8String], -1, SQLITE_TRANSIENT);
Are you sure that first one sould be addStmt?
Given that that's the only place where it's used in the code shown, and in a section clearly designed to populate the eight updateStmt variables, I'd say it's most likely a typo or cut-and-paste error.

Related

Passing variable in query does not show any result

I have table in sqlite I want to get data where userNAme and organizatiocode. problem is that it does not show any rows. If I do not pass variable and select all data then it returns rows.
Here is my code
+(void)getInitialData:(NSString *)dbPath {
MultipleDetailViewsWithNavigatorAppDelegate *appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSLog(#"User NAme is %#",appDelegate.userName);
// const char *sql = "select * from library";
const char *sql = "select * from library where userName=?";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
//sqlite3_bind_text(selectStmt, 1, [appDelegate.userName UTF8String], -1, SQLITE_TRANSIENT);
//sqlite3_bind_text(selectStmt, 1, [appDelegate.organizationCode UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(selectStmt , 1, [appDelegate.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(selectStmt , 2, [appDelegate.organizationCode UTF8String], -1, SQLITE_TRANSIENT);
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.userID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
coffeeObj.contentAddedDateTime = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,2)];
coffeeObj.contentType = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,3)];
coffeeObj.contentTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,4)];
coffeeObj.contentSource = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,5)];
coffeeObj.contentDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,6)];
coffeeObj.categoryTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,7)];
coffeeObj.subCategoryTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,8)];
coffeeObj.organizationCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,9)];
coffeeObj.userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,10)];
int count=[appDelegate.libraryArrayLocal count];
NSLog(#"count is beofore getting values %d",count);
[appDelegate.libraryArrayLocal addObject:coffeeObj];
int countone=[appDelegate.libraryArrayLocal count];
NSLog(#"count is after getting values %d",countone);
[coffeeObj release];
}
}
}
else
sqlite3_close(database);
}
}
Try to use:
NSString *query = [NSString stringWithFormat:#"select * from library where userName=%#",appDelegate.userName];
const char *sql = [query UTF8String];
Instead of:
const char *sql = "select * from library where userName=?";
also try without binding,
if(sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//do your stuff here
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

sqlite3_exec != SQLITE_OK [duplicate]

This question already has answers here:
sqlite3_prepare_v2 != SQLITE_OK
(2 answers)
Closed 9 years ago.
Anybody help me please.
I can't insert the data to sqlite.
the output is "News added failed".
Note :
- The database is already created.
- News is an object
I just think that the problem is in this function.
Could you tell me whats wrong with my code?
Thanks.
- (void)addNews:(NSString *)content_caption content_date:(NSString *)content_date content_desk:(NSString *)content_desk content_id:(NSString *)content_id content_img:(NSString *)content_img content_type:(NSString *)content_type content_web_url:(NSString *)content_web_url{
char *error;
if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK) {
NSString *inserStmt = [NSString stringWithFormat:#"INSERT INTO dBase(CONTENT_CAPTION,CONTENT_DATE, CONTENT_DESK, CONTENT_ID, CONTENT_IMG, CONTENT_TYPE, CONTENT_WEB_URL) values (\'%#\',\'%#\',\'%#\',\'%#\',\'%#\',\'%#\',\'%#\')",content_caption, content_date, content_desk, content_id, content_img, content_type ,content_web_url];
const char *insert_stmt = [inserStmt UTF8String];
if (sqlite3_exec(database, insert_stmt, NULL, NULL, &error)==SQLITE_OK) {
NSLog(#"News added");
News *news = [[News alloc]init];
[news setContent_caption:content_caption];
[news setContent_date:content_date];
[news setContent_desk:content_desk];
[news setContent_id:content_id];
[news setContent_img:content_img];
[news setContent_type:content_type];
[news setContent_web_url:content_web_url];
[arrayOfNews addObject:news];
}else{
NSLog(#"News added failed");
}
sqlite3_close(database);
}
}
try with this
#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
const char *insertSql;
insertSql = nil;
insertSql = "INSERT INTO dBase(CONTENT_CAPTION,CONTENT_DATE, CONTENT_DESK, CONTENT_ID, CONTENT_IMG, CONTENT_TYPE, CONTENT_WEB_URL) values (?,?,?,?,?,?,?)";
if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK) {
sqlite3_bind_text(insert_statement, 1, [content_caption UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 2, [content_date UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 3, [content_desk UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 4, [content_id UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 5, [content_img UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 6, [content_type UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 7, [content_web_url UTF8String], -1, SQLITE_TRANSIENT);
}
First you need to set path of your database . Do like this
// Setting path
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasepath =[docsDir stringByAppendingPathComponent: #"yourDatabase"];
NSFileManager *fn=[NSFileManager defaultManager];
NSError *error;
BOOL success=[fn fileExistsAtPath:databasepath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"quizdb"];
success = [fn copyItemAtPath:defaultDBPath toPath:databasepath error:&error];
}
//Next you have to insert as follows
sqlite3_stmt *statement;
const char *dbpath=[databasepath UTF8String];
if(sqlite3_open(dbpath,&contactDB)==SQLITE_OK)
{
const char *sqlStatement = "insert into dBase(CONTENT_CAPTION,CONTENT_DATE, CONTENT_DESK, CONTENT_ID, CONTENT_IMG, CONTENT_TYPE, CONTENT_WEB_URL) VALUES (?,?,?,?,?,?,?)";
if (sqlite3_prepare_v2(contactDB,sqlStatement,-1,&statement,NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [content_caption UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [content_date UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3 ,[content_desk UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, [content_id UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 5, [content_img UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 6, [content_type UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 7, [content_web_url UTF8String], -1, SQLITE_TRANSIENT);
}
if (sqlite3_step(statement)!= SQLITE_DONE)
{
NSLog(#"Save Error:%s",sqlite3_errmsg(contactDB));
}
else {
NSLog(#"success");
sqlite3_reset(statement);
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
Hope it will helps you..

sqlite Constraint failed

I am developing an app based on sqlite,
When i am inserting data in to database the following error occurs.
Table Structure:
CREATE TABLE "Products" ("ProductBarcode" VARCHAR PRIMARY KEY UNIQUE NOT NULL , "ProductName" VARCHAR NOT NULL , "ProductImage" VARCHAR NOT NULL , "ProductIngredients" VARCHAR NOT NULL , "ProductStatus" VARCHAR NOT NULL )
2011-04-15 10:09:48.408 halalgauge[4517:207] Not Matched
2011-04-15 10:09:48.410 halalgauge[4517:207] *** Assertion failure in -[sqlClass addRecord:], /Users/admin/Desktop/Halal/Classes/sqlClass.m:149
2011-04-15 10:09:48.410 halalgauge[4517:207] Exception occured at add statement, the error is Error while inserting data. 'constraint failed'
The code is:
#import "sqlClass.h"
sqlite3 *database = nil;
sqlite3_stmt *deleteStmt = nil;
sqlite3_stmt *addStmt = nil;
sqlite3_stmt *detailStmt = nil;
sqlite3_stmt *updateStmt = nil;
#implementation sqlClass
#synthesize membersInfoArray,membersInfoDict,rowID;
- (void) copyDatabaseIfNeeded
{
membersInfoArray = [[NSMutableArray alloc]init];
membersInfoDict = [[NSMutableDictionary alloc]init];
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"HalalGauge.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
#try {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"HalalGauge.sqlite"];
}
#catch (NSException * e) {
NSLog(#"Exception");
}
#finally {
//[sqlClass finalizeStatements];
NSLog(#"At Finally block");
}
}
+ (void) finalizeStatements {
if (addStmt) sqlite3_finalize(addStmt);
if (database) sqlite3_close(database);
if (deleteStmt) sqlite3_finalize(deleteStmt);
if (detailStmt) sqlite3_finalize(detailStmt);
if (updateStmt) sqlite3_finalize(updateStmt);
}
- (void) gettingData:(NSString *)dbPath {
NSLog(#"Data base path is %#",dbPath);
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from Products";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
[membersInfoDict setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)] forKey:#"ProductBarcode"];
[membersInfoDict setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)] forKey:#"ProductName"];
[membersInfoDict setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)] forKey:#"ProductImage"];
[membersInfoDict setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)] forKey:#"ProductIngredients"];
[membersInfoDict setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)] forKey:#"ProductStatus"];
if(membersInfoDict)
{
[membersInfoArray addObject:membersInfoDict];
membersInfoDict = nil;
// NSLog(#"Entered and return");
// return;
}
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
- (void) addRecord:(NSMutableDictionary *)recordDict
{
#try {
if(addStmt == nil) {
const char *sql = "insert into Products (ProductBarcode,ProductName,ProductImage,ProductIngredients,ProductStatus) 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, [[recordDict objectForKey:#"ProductBarcode"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [[recordDict objectForKey:#"ProductName"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [[recordDict objectForKey:#"ProductImage"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [[recordDict objectForKey:#"ProductIngredients"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 5, [[recordDict objectForKey:#"ProductStatus"] UTF8String], -1, SQLITE_TRANSIENT);
//NSLog(#"the values are %#",addStmt);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
rowID = sqlite3_last_insert_rowid(database);
NSLog(#"last inserted rowId = %d",rowID);
sqlite3_close(database);
}
#catch (NSException * e) {
NSLog(#"Exception occured at add statement, the error is %# ",e);
}
#finally {
[sqlClass finalizeStatements];
}
}
#end
may be it's not a "not null" constrain but "ProductBarcode" PRIMARY KEY UNIQUE?
did you check you product barcode uniqueness???
I solved my problem with the following code:
- (void) addRecord:(NSMutableDictionary *)recordDict
{
#try {
[self checkAndCreateDatabase];
if (sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK) {
NSString *statement;
sqlite3_stmt *compiledstatement;
NSString *ProductName,*ProductBarcode,*ProductImage,*ProductIngredients,*ProductStatus;
ProductName = [recordDict objectForKey:#"ProductName"];
ProductBarcode = [recordDict objectForKey:#"ProductBarcode"];
ProductImage = [recordDict objectForKey:#"ProductImage"];
ProductIngredients = [recordDict objectForKey:#"ProductIngredients"];
ProductStatus = [recordDict objectForKey:#"ProductStatus"];
statement = [[NSString alloc]initWithFormat:#"insert into Products values('%#','%#','%#','%#','%#')",ProductBarcode,ProductName,ProductImage,ProductIngredients,ProductStatus];
const char *sqlstatement = [statement UTF8String];
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compiledstatement, NULL)== SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compiledstatement) ) {
NSAssert1(0,#"Error when inserting %s",sqlite3_errmsg(database));
}
else {
NSLog(#"Data inserted Successfully");
}
sqlite3_finalize(compiledstatement);
}
sqlite3_close(database);
}
}
#catch (NSException * e) {
NSLog(#"The Record already inserted ");
}
}

sqlite3 crashes for second insert statement

My App is crashing on statement (sqlite3_step(insertAlert) == SQLITE_DONE) when executed for i = 1. Can anybody tell me why it is crashing?
sqlite3_stmt *insertAlert;
textmeAppDelegate *textme = (textmeAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *insert = #"INSERT INTO alerts (alert_id, email_address, messege_text, when_to_send, how_often_send, recipient_phone_number) VALUES(?, ?, ?, ?, ?, ?)";
if(sqlite3_prepare_v2(textme.dbConn, [insert UTF8String], -1, &insertAlert, NULL) == SQLITE_OK)
{
NSDictionary *tmpDictionary;
NSString *alertId;
for(int i=0; i<[keys count]; i++)
{
alertId = [NSString stringWithFormat:#"%#", [keys objectAtIndex:i]];
tmpDictionary = [NSDictionary dictionaryWithDictionary:[dictionary2 objectForKey:alertId]];
sqlite3_bind_text(insertAlert, 1, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"alert_id"]], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertAlert, 2, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"email_address"]], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertAlert, 3, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"messege_text"]], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertAlert, 4, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"when_to_send"]], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertAlert, 5, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"how_often_send"]], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertAlert, 6, [NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"recipient_phone_number"]], -1, SQLITE_TRANSIENT);
if (sqlite3_step(insertAlert) == SQLITE_DONE) {
sqlite3_reset(insertAlert);
sqlite3_clear_bindings(insertAlert);
}
else {
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(textme.dbConn));
//[textme showError:#"Device Error" errMsg:sqlite3_errmsg(textme.dbConn)];
return FALSE;
}
}
sqlite3_finalize(insertAlert);
}
Do you think sqlite3_bind_text() understands what to do with an NSString? I don't.
I'm surprised that
it works even when i == 0
you aren't seeing a compiler warning on all of those binds.
To fix you need to replace
[NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"alert_id"]]
with
[[NSString stringWithFormat:#"%#", [tmpDictionary objectForKey:#"alert_id"]] UTF8String]
and similarly for all the other sqlite3_bind_text() lines.

Why can't I execute this code?

NSString *event=#"max";
NSString *venue=#"tvm";
NSString *edate=#"may 6";
NSString *etime=#"10:30";
int admts=5;
NSString *ima=ticobj.iimg;
sqlite3 *database;
databaseName = #"smbhDB.sql";
sqlite3_stmt *addStatement ;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
if(addStatement == nil) {
const char *sql ="insert into tickets (admittance, venue, event, date, time, imagedata) Values (?,?,?,?,?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStatement, NULL) != SQLITE_OK)
NSAssert1(0, #"444 Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_int(addStatement,1,admts);
sqlite3_bind_text(addStatement, 2, [venue UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 3, [event UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 4, [edate UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 5, [etime UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 6, [ima UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStatement))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
if(sqlite3_prepare_v2(database, sql, -1, &Statement, NULL) == SQLITE_OK) {
sqlite3_exec(database, sql, -1, &Statement, NULL);
}
sqlite3_reset(addStatement);
Why can't I execute this code?
Where is
sqlite3_open([databasePath UTF8String], &database); ?
You can't work with a closed database.
-(BOOL)insertDatabaseValue:(SignIn *)objFavourie isUpdate:(BOOL)update
{
BOOL returnValue = YES;
sqlite3_stmt *insertStmt = nil;
sqlite3 *database = nil;
if (sqlite3_config(SQLITE_CONFIG_SERIALIZED) == SQLITE_OK){
returnValue = NO;
}
if (sqlite3_open([DataBasePath UTF8String], &database) == SQLITE_OK){
if(insertStmt == nil) {
NSString *aString;
if(!update)
aString =[NSString stringWithFormat:#"INSERT INTO Sanjay('Name', 'Password') Values(?, ?)"];
else
aString =[NSString stringWithFormat:#"UPDATE Sanjay SET Password = ? where 'Name'=%#",objFavourie.strName];
const char *sql = [aString UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &insertStmt, NULL) != SQLITE_OK)
{
NSLog(#"Error while creating insert :%s add statement.", sqlite3_errmsg(database));
returnValue = NO;
}
}
if(sqlite3_bind_text(insertStmt, 1, [objFavourie.strName UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK){
returnValue = NO;
}
if(sqlite3_bind_text(insertStmt, 2, [objFavourie.strPassword UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
returnValue = NO;
}
if(SQLITE_DONE != sqlite3_step(insertStmt)){
NSLog(#"Error while inserting into '%s'", sqlite3_errmsg(database));
returnValue = NO;
}
sqlite3_reset(insertStmt);
if (insertStmt) {
sqlite3_finalize(insertStmt);
insertStmt = nil;
}
sqlite3_close(database);
database = nil;
}
else {
returnValue = NO;
}
return returnValue;
}