When I am inserting my array elements into sqlite, it is inserting properly. It takes only the first element in array, for remaining it is showing error while inserting. My code is:
NSString *path=[self getDBPath];
sqlite3_stmt *insert_statement = nil;
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
for (int i = 0; i < [array count]; i++)
{
NSLog(#"Array Count is %d",[array count]);
NSString *name=[[array objectAtIndex:i]objectForKey:#"name"];
NSString *add=[[array objectAtIndex:i]objectForKey:#"address"];
if (insert_statement == nil) {
NSString *statement1 = [NSString stringWithFormat:#"insert into tableName (name,address) Values( ?,?)",name,add];
const char *insertSql = [statement1 UTF8String];
if(sqlite3_prepare_v2(database, insertSql, -1, &insert_statement, NULL) != SQLITE_OK){
NSLog(#"Error while creating insert statement.");
insert_statement = nil;
continue;
}
sqlite3_bind_text(insert_statement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 2, [add UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insert_statement)){
//NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
NSLog(#"Error while inserting data.");
insert_statement = nil;
continue;
}
else{}
sqlite3_reset(insert_statement);
sqlite3_finalize(insert_statement);
insert_statement = nil;
}
}
sqlite3_close(database);
}
Why does it allow only one record?
It's occurred due to finalize statement in loop every time. So it wont let insert other objects after the first object.
Just remove "sqlite3_finalize(insert_statement);" from the loop and set nil to the insert statement "insert_statement = nil;"
After done with loop. Make sure place the "sqlite3_reset(insert_statement);" for each object in the loop. It reset the statement and there is no need to set nil to the statement in loop.
Try this piece of code, it works for me:
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
for (int i = 0; i < [array count]; i++)
{
NSLog(#"Array Count is %d",[array count]);
NSString *name=[[array objectAtIndex:i]objectForKey:#"name"];
NSString *add=[[array objectAtIndex:i]objectForKey:#"address"];
if (insert_statement == nil) {
NSString *statement1 = [NSString stringWithFormat:#"insert into tableName (name,address) Values( ?,?)",name,add];
const char *insertSql = [statement1 UTF8String];
if(sqlite3_prepare_v2(database, insertSql, -1, &insert_statement, NULL) != SQLITE_OK){
NSLog(#"Error while creating insert statement.");
insert_statement = nil;
continue;
}
sqlite3_bind_text(insert_statement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 2, [add UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insert_statement)){
//NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
NSLog(#"Error while inserting data.");
insert_statement = nil;
continue;
}
else{
sqlite3_reset(insert_statement);
}
}
}
insert_statement = nil;
sqlite3_finalize(insert_statement);
sqlite3_close(database);
}
try this code its works for me
for(int i=0;i<[data count];i++)
{
NSMutableDictionary *myDict = [data objectAtIndex:i];
selectSql=[NSString stringWithFormat:#"INSERT INTO [commentTable] values('%#','%#')",[myDict valueForKey:#"usertype"],[myDict valueForKey:#"userid"]];
if (sqlite3_prepare_v2(database, [selectSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
ret = YES;
NSLog(#"DB SUPPORT - commentTable INSERTED");
}
else
{
NSLog(#"DB SUPPORT - ERROR commentTable INSERT");
}
}
else
{
NSLog(#"DB SUPPORT - Sql Preparing Error ( INSERT commentTable)");
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
You can use :
for (int i = 0; i < [mutArray count]; i++)
{
NSString *string = [mutArray objectAtIndex:i];
// insert query
insert into table_name ('string') values(column_name);
}
Ref : How to add nsmutable array into sqlite database table
Related
I stored some images in my server. And try to get this images from URL and store to local database then try to access. But the images are not storing to database. But when i use log it displaying inserting all the values. But i can't shown in db via SQLiteManager
code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
// [overlayButton setFrame:CGRectMake(80, 420, 60, 30)];
[btn setFrame:CGRectMake(50, 50, 30, 30)];
[btn addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
Button click:
-(void)click:(id)sender{
NSLog(#"click");
NSString *databasePath=[[NSBundle mainBundle]pathForResource:#"db1" ofType:#"sqlite"];
NSError *err=nil;
NSFileManager *fm=[NSFileManager defaultManager];
NSArray *arrPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, -1);
NSString *path=[arrPaths objectAtIndex:0];
NSString *path2= [path stringByAppendingPathComponent:#"db1.sqlite"];
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(!success){
NSLog(#"file copied successfully");
}
/*
if(![fm fileExistsAtPath:path2])
{
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(success)
NSLog(#"file copied successfully");
else
NSLog(#"file not copied");
}
*/
NSURL *URL = [NSURL URLWithString:#"http://myserver.net/projects/mobile/jsonstring.php"];
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:URL
encoding:NSUTF8StringEncoding
error:&error];
//NSLog(#"response is %#", stringFromFileAtURL);
// NSString *path = [documentsDirectory stringByAppendingPathComponent:#"db1.sqlite"];
//NSLog(#"filepath %#",path);
NSString *path1 = [path stringByAppendingPathComponent:#"db1.sqlite"];
//NSDictionary *jsonDict = [stringFromFileAtURL JSONValue];
//array
NSArray *userData = [stringFromFileAtURL JSONValue];
[stringFromFileAtURL release];
int i = 0;
BOOL notExist = TRUE;
sqlite3_stmt *statement, *addStmt;
for (NSArray *skarray in userData) {
//NSLog(#"test");
if(i == 0){
//insert all main category
for (NSDictionary *tuser in skarray) {
//write all this in the table
//if already exists in data base id then overwrite the name
//category table
//NSLog(#"CategoryId is %#",[tuser objectForKey:#"cat_id"]);
//NSLog(#"CategoryName is %#",[tuser objectForKey:#"cat_name"]);
if (sqlite3_open([path1 UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:#"SELECT id FROM categories where id = '%#'",[tuser objectForKey:#"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"categories select is %s", sql);
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
if(notExist){
//NSLog(#"cat id does not exist");
const char *sqlInsert = [[NSString stringWithFormat:#"insert into categories (id,cat_name,order_by) values('%#','%#','%#')", [tuser objectForKey:#"id"], [tuser objectForKey:#"cat_name"],[tuser objectForKey:#"order_by"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"categories insert is %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
}
if(i == 1){
//insert all main category
for (NSDictionary *tuser in skarray) {
//write all this in the table
//if already exists in data base id then overwrite the name
//category table
//NSLog(#"CategoryId is %#",[tuser objectForKey:#"cat_id"]);
//NSLog(#"CategoryName is %#",[tuser objectForKey:#"cat_name"]);
if (sqlite3_open([path1 UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:#"SELECT product_image FROM product where cat_id = '%#'",[tuser objectForKey:#"id"]] cStringUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"product select is %s", sql);
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
notExist = TRUE;
while (sqlite3_step(statement) == SQLITE_ROW) {
notExist = FALSE;
}
}
if(notExist){
//NSLog(#"cat id does not exist");
// imgData = UIImagePNGRepresentation([tuser objectForKey:#"product_image"]);
// sqlite3_bind_blob(addStmt, 6, [imgData bytes], [imgData length], NULL);
const char *sqlInsert = [[NSString stringWithFormat:#"insert into product (id, cat_id,product_image,order_by) values ('%#','%#','%#','%#')", [tuser objectForKey:#"id"], [tuser objectForKey:#"cat_id"],[tuser objectForKey:#"product_image"],[tuser objectForKey:#"order_by"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"product insert %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
}
if(i == 2){
//insert all main category
for (NSDictionary *tuser in skarray) {
NSLog(#"version id is %#",[tuser objectForKey:#"product_id"]);
const char *sqlInsert = [[NSString stringWithFormat:#"insert into version_app (id) values ('%#')", [tuser objectForKey:#"product_id"]] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(#"stmt is %s", sqlInsert);
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) == SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE == sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
i++;
}
}
Do you see anything wrong here:
bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
if(!success){
NSLog(#"file copied successfully");
}
i am inserting data into data base using following code but data is not inserted in the database
i am using following code
I am inserting data into iphone application but it does not insert
i have table survey_question_master(question_id,question_text,question_type)
- (void) addCoffee {
if(addStmt == nil) {
const char *sql = "insert into survey_question_master(question_text,question_type) 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, [question_text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [question_type UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
question_ID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
- (void) addCoffee:(DataController *)coffeeObj {
//Add it to the database.
[coffeeObj addCoffee];
//Add it to the coffee array.
[coffeeArray addObject:coffeeObj];
NSLog(#"Succeessfully Added");
}
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"database.sqlite"];
}
-(void)SaveData:(NSMutableArray *)insertDataArray
{
sqlite3_stmt *stmt;
const char *dbPath = [[self getDBPath] UTF8String];
if(sqlite3_open(dbPath, &database)==SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into items (c1,c2,c3,c4 , c5 ,c6,c7,c8,c9) values (\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")",[insertDataArray objectAtIndex:0],[insertDataArray objectAtIndex:1],[insertDataArray objectAtIndex:2],[insertDataArray objectAtIndex:3],[insertDataArray objectAtIndex:4],[insertDataArray objectAtIndex:5],[insertDataArray objectAtIndex:6],[insertDataArray objectAtIndex:7],[insertDataArray objectAtIndex:8]];
NSLog(#"%#",insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt, -1, &stmt, NULL);
if(sqlite3_step(stmt)==SQLITE_DONE)
{
NSLog(#"insert success");
}
else
{
NSLog(#"insert un success");
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int success=sqlite3_step(stmt);
if (success == SQLITE_ERROR)
{
NSAssert1(0, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
} sqlite3_finalize(stmt);
sqlite3_close(database);
}
}
I am creating a database to store the value in table with a primary key but I am getting a problem with the primary key. It is not taking. If I enter the first time it's shown in the database record but if I enter a second time the record is not showing in the database. My application shows bad access in the console.
+(void) getInitialDataToDisplay:(NSString *)dbPath
{
SqltestAppDelegate *appDelegate =(SqltestAppDelegate *)[[UIApplication sharedApplication]delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select JourneyID,JourneyName,LocationName,Description from UserJourney";
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);
NewJourney *newobj = [[NewJourney alloc]initWithPrimaryKey:primaryKey];
newobj.journeyName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
newobj.isDirty = NO;
[appDelegate.journeyList addObject:newobj];
[appDelegate.journeyList release];
}
}
}
else {
sqlite3_close(database);
}
}
+(void) finalizeStatements
{
if (database) sqlite3_close(database);
if (database) sqlite3_finalize(deleteStmt);
if (database) sqlite3_finalize(addStmt);
if (database) sqlite3_finalize(detailSmt);
if (database) sqlite3_finalize(updateStmt);
}
-(id) initWithPrimaryKey:(NSInteger)pk
{
[super init];
journeyID = pk;
isDetailViewHydrated = NO;
return self;
}
-(void) deleteCoffee
{
if (deleteStmt == nil)
{
const char *sql = "delete from UserJourney where JourneyID = ?";
if (sqlite3_prepare_v2(database, sql, -1, &deleteStmt,NULL) != SQLITE_OK)
{
NSAssert1(0,#"Error while creating delete statemnet.'%s'",sqlite3_errmsg(database));
}
//when binding parameters, index starts from 1 and not zero.
sqlite3_bind_int(deleteStmt, 1, journeyID);
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 UserJourney(JourneyName,LocationName,Description) 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 , [journeyName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2 , [locationName UTF8String],-1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [description UTF8String],-1, SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(addStmt))
{
NSAssert1(0,#"Error while inserting data. '%s'",sqlite3_errmsg(database));
}else
{
journeyID = sqlite3_last_insert_rowid(database);
}
sqlite3_reset(addStmt);
}
}
/*-(void) hydrateDetailViewData
{
if (isDetailViewHydrated) return;
if (detailSmt == nil) {
const char *sql = "select JourneyName,Description from UserJourney where JourneyID = ?";
if (sqlite3_prepare_v2(database, sql, -1, &detailSmt,NULL) != SQLITE_OK)
NSAssert1(0,#"Error while creating detail view statement. '%s'",sqlite3_errmsg(database));
}
sqlite3_bind_int(detailSmt,1,journeyID);
if (SQLITE_DONE != sqlite3_step(detailSmt))
{
<#statements#>
}
}*/
-(void)saveAllData
{
if (isDirty) {
if (updateStmt == nil) {
const char *sql = "update UserJourney Set JourneyName = ?,LocationName = ?, Description = ? Where JourneyID =?";
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, [journeyName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [locationName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3, [description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt,4, journeyID);
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(updateStmt);
isDirty = NO;
}
[journeyName release];
journeyName = nil;
isDetailViewHydrated = NO;
}
You have to release your newobj not the array.
Replace this:
[appDelegate.journeyList release];
with this:
[newobj release];
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 ");
}
}
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;
}