I am trying to insert data into my SQLite database. I have imported all the neccassry frameworks and database files nedded for my project. In my controller class xib there are two textfields and a button. I want the data entered into both of the text fields saved in my database when I click on the button.
In my app delagate I have created two functions, one function to append the path of the database, and the other to insert data into the database. In the insert function, I check for certain conditions, i.e., if data gets added, an alert view should be displayed showing the record added, but when I add a new record it always goes into the else block, which is an error.
-(void)checkAndCreateDB {
NSString* databaseName = #"login.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)insertData{
sqlite3 *database;
sqlite3_stmt *statement;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO Loginchk (uname,password) VALUES ('%#',' %#');",Gunameq,Gpassq];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [Gunameq UTF8String], -1, NULL);
sqlite3_bind_text(statement, 2, [Gpassq UTF8String], -1, NULL);
}
if(sqlite3_step(statement)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Add Record" message:#"Contact Added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"record" message:#"record not created" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
This is my login controller class. Here I have declared a function through which I access my app delegate's functions.
-(IBAction)buttonPressed:(id)sender
{
Gpassq=Password.text;
Gunameq=Uname.text;
NSLog(#"%#%#",Gunameq,Gpassq);
AddListAppDelegate *appDelegate =(AddListAppDelegate *)[[UIApplication sharedApplication]delegate];
[appDelegate insertData];
}
Please solve this problem.
static sqlite3_stmt *insertStmt = nil;
if(insertStmt == nil)
{
insertSql = "INSERT INTO Loginchk (uname,password) VALUES(?,?)";
if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(insertStmt, 1, [Gunameq UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 2, [Gpassq UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insertStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
NSLog("Inserted");
//Reset the add statement.
sqlite3_reset(insertStmt);
insertStmt = nil;
In above you can see. If you are binding data no need to have stringWithFormat. Just put question marks and than bind text.
Hope it helps.
this code may be run
-(void) insert:key1:key2:key3
{
databaseName= #"db3.sqlite";
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDir=[documentPaths objectAtIndex:0];
databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *stmnt=[[[NSString alloc]initWithFormat:#"insert into login values(\"%#\",\"%#\",\"%#\")", key1,key2,key3] autorelease];
const char *sqlStatement = [stmnt UTF8String];
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement,NULL) == SQLITE_OK)
{
if (SQLITE_DONE!=sqlite3_step(compiledStatement))
{
UIAlertView *al=[[UIAlertView alloc] initWithTitle:#"INFO"
message:#"Registration Fail"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[al show];
[al release];
}
else {
UIAlertView *al=[[UIAlertView alloc] initWithTitle:#"INFO"
message:#"Registerd"
delegate:self
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[al show];
[al release];
}
}
sqlite3_reset(compiledStatement);
}
sqlite3_close(database);
}
-(IBAction)clicked:(id)sender
{
NSString *t1=[[NSString alloc]initWithFormat:#"%#",txt1.text];
NSString *t5=[[NSString alloc]initWithFormat:#"%#",txt2.text];
NSString *t3=[[NSString alloc]initWithFormat:#"%#",txt3.text];
//NSString *t2=[[NSString alloc]init];
//NSInteger t3;
//NSString *t3=[[NSString alloc]init];
//t1=txt1.text;
//t2=txt2.text;
//t3=txt3.text;
[self insert:t1:t5:t3];
}
another way around for insert is
// Create insert statement for the address
NSString *insertStatement = [NSString stringWithFormat:#"INSERT INTO ADDRESS (STREETNAME, STREETNUMBER, PERSONID) VALUES (\"%#\", \"%#\", \"%d\")", person.address.streetName, person.address.streetNumber, personID];
if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Person inserted.");
}
else
{
NSLog(#"Error: %s", error);
}
Try this code:
-(void)addItem{
//for saving the data into database
if(addStmt == nil) {
const char *sql = "insert into employee(name, address) 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, [name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [address UTF8String], -1, SQLITE_TRANSIENT);
NSLog(#"%#",name);
NSLog(#"%#",address);
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
rowID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
//for retrieving data from database
InsertDataAppDelegate *appDelegate = (InsertDataAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select name, address from employee";
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);
//NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Item *Obj = [[Item alloc]initWithPrimaryKey:primaryKey];
Obj.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
Obj.address=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
Obj.isDirty = NO;
[appDelegate.array addObject:Obj];
[Obj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
- (IBAction)sbumitbuttoncliked:(id)sender
{
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"somefile1.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *statment = nil;
NSString *queryString = [NSString stringWithFormat:#"Insert into form1 (name,password,phoneno)values(\'%#\',\'%#\',\'%#\')",textobj1.text, textobj2.text,textobj3.text];
NSLog(#"%#",queryString);
const char *sql = [queryString UTF8String];
sqlite3_prepare_v2(database, sql, -1, &statment, NULL);
if (textobj1.text.length==0||textobj2.text.length==0||textobj3.text.length==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Not Registered " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil ];
[alert show];
}
else if (sqlite3_step(statment) == SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"you have successfully registered" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil ];
[alert show];
[self dismissModalViewControllerAnimated:YES];
}
sqlite3_finalize(statment);
}
Related
Hello I am new in sqlite database, I want to show data which I have stored in database, in second view controller by clicking (show data button) in tableview.
Below is my code for database
file DBManager.h
#interface DBManager : NSObject
{
NSString *databasePath;
}
+(DBManager*)getSharedInstance;
-(BOOL)createDB;
-(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
department:(NSString*)department year:(NSString*)year;
-(NSArray*) findByRegisterNumber:(NSString*)registerNumber;
#end
file DBManager.m
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
+(DBManager *)getSharedInstance
{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB
{
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSLog(#"%#", docsDir);
databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"student.db"]];
BOOL isSuccess = YES;
NSFileManager *filemngr = [NSFileManager defaultManager];
if ([filemngr fileExistsAtPath:databasePath] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char * sql_stmt = "create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else
{
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}
return isSuccess;
}
-(BOOL)saveData:(NSString *)registerNumber name:(NSString *)name department:(NSString *)department year:(NSString *)year;
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into studentsDetail (regno,name,department,year) values (\"%ld\",\"%#\",\"%#\",\"%#\")",(long)[registerNumber integerValue],name,department,year];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else
{
return NO;
}
//sqlite3_reset(statement);
}
return NO;
}
- (NSArray*) findByRegisterNumber:(NSString*)registerNumber
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"select name,department,year from studentsDetail where regno=\"%#\"",registerNumber];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:name];
NSString *department = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
[resultArray addObject:department];
NSString *year = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
[resultArray addObject:year];
NSLog(#"%#", resultArray);
return resultArray;
}
else{
NSLog(#"Not found");
return nil;
}
//sqlite3_reset(statement);
}
}
return nil;
}
#end
Please help me..
Updated Code:
DBManager.m
-(NSArray *) showdata{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM studentsDetail"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultentArray=[[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *resultentDict = [[NSMutableDictionary alloc] init];
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
NSString * department = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
NSString *year = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
NSLog(#"%#",resultentDict);
[resultentDict setValue:name forKey:#"name"];
[resultentDict setValue:department forKey:#"department"];
[resultentDict setValue:year forKey:#"year"];
NSLog(#"%#",resultentDict);
NSLog(#"%#",resultentArray);
[resultentArray addObject:resultentDict];
NSLog(#"%#",resultentArray);
}
return resultentArray;
}
sqlite3_close(database);
}
return nil;
}
after that I created one button called show data ... if I click that it will navigate to another TableViewController:
I implemented like this :
in TableViewController:
- (void)viewDidLoad {
[self showData];
}
-(void)showData{
data = [[DBManager getSharedInstance]showdata];
NSLog(#"DATA %#",data);
NSLog(#"%lu",(unsigned long)[[data valueForKey:#"price"] count]);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[data valueForKey:#"price"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSLog(#"%#",data);
// cell.textLabel.text = [[data valueForKey:#"year"]objectForKey:indexPath.row];
cell.textLabel.text=[[data valueForKey:#"price"]objectAtIndex:indexPath.row];
return cell;
}
HI I am using update statement for updating the record in sqlite database. Please help me what is the wrong in my code. i am not understanding where it is wrong. i am using the below code
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Notes.sqlite"];
sqlite3_stmt *updateStmt = nil;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = [[NSString stringWithFormat:#"update Notess Set Name=? Where NoteId = %#",_notesId] UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. %s", sqlite3_errmsg(database));
}else{
}
sqlite3_bind_text(updateStmt, 1, [textVew.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_finalize(updateStmt);
sqlite3_close(database);
You have failed to call sqlite3_step after your sqlite3_bind_text statement. Thus, you never actually performed the SQL.
Thus, it should look like:
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Notes.sqlite"];
sqlite3_stmt *updateStmt = nil;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = [[NSString stringWithFormat:#"update Notess Set Name=? Where NoteId = %#",_notesId] UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. %s", sqlite3_errmsg(database));
if (sqlite3_bind_text(updateStmt, 1, [textVew.text UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK)
NSLog(#"Error while binding value. %s", sqlite3_errmsg(database));
if (sqlite3_step(updateStmt) != SQLITE_DONE)
NSLog(#"Error during step. %s", sqlite3_errmsg(database));
sqlite3_finalize(updateStmt);
sqlite3_close(database);
}else{
NSLog(#"Error while opening database");
}
I'm trying to add new row to TableView with edit mode. Used this tutorial. But after dismissing my edit mode view my table view is not reloaded. My addItem: method
- (IBAction)addItem:(id)sender {
BIDAppDelegate *appDelegate = (BIDAppDelegate *)[[UIApplication sharedApplication] delegate];
sqlite3 *database;
NSString *databaseName;
NSString *databasePath;
databaseName = #"TestProjectDatabase.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if(!success) {
databasePath = [[NSBundle mainBundle] pathForResource:databaseName ofType:nil];
}
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into \"MyItems\" ( \"MyItemName\", \"MyItemDescription\") values ( '%#', '%#');", _nameTextField.text, _descriptionTextField.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, insert_stmt, -1, &compiledStatement, NULL) != SQLITE_OK)
{
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}else{
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
// NSLog(#"All ok");
} else {
// NSLog(#"FAIL");
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
MyItems *itemsToDatabase = [[MyItems alloc] initWithItemName:_nameTextField.text andItemDescription:_descriptionTextField.text];
[appDelegate.myItems addObject:itemsToDatabase];
[self dismissModalViewControllerAnimated:YES];
}
SQL insertion is OK because where is new row after restarting my project. Any suggestions how to fix it?
Assuming the table data source reads from appDelegate.myItems, you just need to reload the table itself [tableView reloadData];.
I tried to update an entry in my table like this:
NSFileManager *fileMgr=[NSFileManager defaultManager];
NSString *dbPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"quizDB.sqlite"];
if ([fileMgr fileExistsAtPath:dbPath]) {
NSLog(#"DB does exist!");//displayed
}
const char *dbpath = [dbPath UTF8String];
sqlite3_stmt *updateStmt;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"%i",id_quiz);//displayed, in a test case it display 1 which is a quiz ID in the table
NSString *querySql=[NSString stringWithFormat:#"Update quiz set etat=1 where id=\"%i\"",id_quiz];
const char*sql=[querySql UTF8String];
sqlite3_prepare_v2(contactDB, sql, -1, &updateStmt, NULL);
if(SQLITE_DONE != sqlite3_step(updateStmt))
{
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(contactDB));
}
else{
sqlite3_reset(updateStmt);
NSLog(#"Update done successfully!");//this is also displayed, i guess everything is ok then and the entry is updated
}
sqlite3_finalize(updateStmt);
sqlite3_close(contactDB);
}
In the log, i got the message: Update done successfully! so i assumed that everything is, however when i check the database within SQLite Manager in Mozilla Firefox, the entry is not updated. Am i missing something? thanx for help
first copy your database from resource to document dir:
- (void) checkAndCreateDatabase
{
NSString *database_Name =#"quizDB.sqlite"
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *database_Path = [documentsDir stringByAppendingPathComponent:database_Name];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:database_Path])
{
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:database_Name];
[fileManager removeItemAtPath:database_Path error:nil];
[fileManager copyItemAtPath:databasePathFromApp toPath:database_Path error:nil];
}
else
{
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:database_Name];
[fileManager copyItemAtPath:databasePathFromApp toPath:database_Path error:nil];
}
}
and after you update your database:
- (void) UpdateDatabase
{
sqlite3 *contactDB;
sqlite3_stmt *updateStmt;
NSString *database_Name =#"quizDB.sqlite"
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *dbpath = [documentsDir stringByAppendingPathComponent:database_Name];
if(sqlite3_open([dbpath UTF8String], &contactDB) == SQLITE_OK)
{
NSString *querySql=[NSString stringWithFormat:#"Update quiz set etat=1 where id=\"%i\"",id_quiz];
const char*sql=[querySql UTF8String];
if(sqlite3_prepare_v2(contactDB,sql, -1, &updateStmt, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(updateStmt))
{
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(contactDB));
}
else{
sqlite3_reset(updateStmt);
NSLog(#"Update done successfully!");
}
}
sqlite3_finalize(updateStmt);
}
sqlite3_close(contactDB);
}
and check your database which save in documentdir not in resource
I am trying to add 3 pieces of data to a SQLite3 DB. With help from a tutorial, I'm almost there. Below is my code.
I am receiving what I would expect from the NSLogs. I find the DB without problem, I compile the statement to send to the DB without problem, but when the app gets to sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK I am expecting the data to be added to the DB, but it isn't, and I'm also expecting to display a UIAlertView to tell the user ERROR os SUCCESS. I hope you can see what I do not.
- (IBAction)addData:(id)sender {
NSString *n = [[NSString alloc] initWithString:[name text]];
NSString *a = [[NSString alloc] initWithString:[age text]];
NSString *c = [[NSString alloc] initWithString:[color text]];
NSLog(#"%# - %# - %#",n,a,c);
[self insertDataName:n Age:a Color:c];
}
This NSLog returns the text properties as expected.
- (IBAction)hide:(id)sender {
[name resignFirstResponder];
[age resignFirstResponder];
[color resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
DBName = #"mydatabase.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentsPaths objectAtIndex:0];
DBPath = [documentsDir stringByAppendingPathComponent:DBName];
}
-(void)checkAndCreateDB {
BOOL Success;
NSFileManager *fileManager = [NSFileManager defaultManager];
Success = [fileManager fileExistsAtPath:DBPath];
if(Success) {
NSLog(#"DB Found");
return;
}
NSLog(#"DB Not Found");
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];
[fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
}
This NSLog returns DB Found
-(void)insertData Name:(NSString*)n Age:(NSString*)a Color:(NSString*)c {
[self checkAndCreateDB];
sqlite3 *database;
if (sqlite3_open([DBPath UTF8String],&database)==SQLITE_OK) {
NSString *statement;
sqlite3_stmt *compliedstatement;
statement = [[NSString alloc] initWithFormat:#"insert into table1 values ('%#', '%#', '%#')",n,a,c];
const char *sqlstatement = [statement UTF8String];
NSLog(#"%#",statement);
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
NSAssert1(0, #"Error by inserting '%s'", sqlite3_errmsg(database));
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error by inserting" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[AlertOK show];
}
else {
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Data successfully inserted" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[AlertOK show];
}
}
sqlite3_finalize(compliedstatement);
}
sqlite3_close(database);
}
And the last NSLog above displays insert into table1 values ('n', 'a', 'c') as I would expect.
Something is going wrong upon insertion and I can't figure it out.
FYI the DB was created using SQLiteManager. SS below:
Ok, Are you working on a simulator or an iDevice? In iDevice, you cannot create an external SQL database (at least to my knowledge). You have to create it dynamically because of the sandboxing. "FYI the DB was created using SQLiteManager." Check on that.
If that was not the problem try changing your code from "prepare ..." to "execute"
From...
if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) {
if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {
NSAssert1(0, #"Error by inserting '%s'", sqlite3_errmsg(database));
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error by inserting" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[AlertOK show];
}
else {
UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Data successfully inserted" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[AlertOK show];
}
}
sqlite3_finalize(compliedstatement);
To...
sqlite3_exec(database, [sqlstatement UTF8String], NULL, NULL, &error);
Do a log on "error" because that is very essential.
if you wanted to pop a UIAlert do this
if (error !=nil)
//show alert for error
else
//show alert for success