how to save the data in sqlite3 in iphone - iphone

i am trying to create the database using sqlite manager.But the values are not stored in database.If i click the save button the Alert Message will be displayed on like this "Data Insertion Failed".i am trying to rectify these problem.In this case i visit so many tutorials.But i cant rectify my problem.Yesterday onwards i am totally blocked to this issue.please give me any idea or suggestion how to save the data.Thanks for all to visit the question.T.C.
DataBase.m
// creation of DATABASE
-(BOOL)createDB
{
NSString *docsDir;
NSArray *dirPaths;
// Get the document directory
dirPaths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
docsDir=dirPaths[0];
// Build the path to the database file
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"Feedback.db"]];
BOOL isSuccess=YES;
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:databasePath]==0)
{
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK)
{
char *errMsg;
const char *sql_stmt= "create table if not exists Feeback details (Traineeid integer, Trainername text,Traineename text,Rating float)";
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;
}
// save data in the Database
-(BOOL) saveData:(NSString *)Traineeid Trainername:(NSString *)Trainername Traineename:(NSString *)Traineename Rating:(NSString *)Rating;
{
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK)
{
NSString *insertSQL=[NSString stringWithFormat:#"insert into Feedbackdetails(Traineeid,Trainername,Traineename,Rating) values(\"%d\",\"%#\", \"%#\", \"%#\")",[Traineeid integerValue],Trainername,Traineename,Rating];
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;
}
FeebBackForm.m
-(IBAction)saveData:(id)sender
{
BOOL success=NO;
NSString *alertString = #"Data Insertion failed";
if (Traineeid.text.length>0 &&Trainername.text.length>0 &&Traineename.text.length>0 &&Rating.text.length>0)
{
success=[[DBManager getSharedInstance]saveData:Traineeid.text Trainername:Trainername.text Traineename:Traineename.text Rating:Rating.text];
}
else
{
alertString = #"Enter all fields";
}
if (success == NO)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:alertString message:nil
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}

Your putting string quotes around your int params in your sql statement.
This may not be your only issue but you should bind params. It looks like you're putting quotes around integer values in the sql insert statement which are defined as integers in your table.
"create table if not exists Feeback details (Traineeid integer, Trainername text,Traineename text,Rating float)"
"insert into Feedbackdetails(Traineeid,Trainername,Traineename,Rating) values(\"%d\",\"%#\", \"%#\", \"%#\")"
Notice your double quotes around ints.
Also, log out the path to your database (even if running in simulator). Go to the sqlite cmd line and ensure the db exists and the empty table is there. This helps in troubleshooting.
Finally, take a look # the fmdb sqlite wrapper - it helps using sqlite but it's code also shows good patterns for using sqlite raw if that's your preference.
Here's a similar function from one of my samples which shows how to bind params. You should also finalize what you prepare:
- (void)updateContact: (Contact*)contact error:(NSError**)error
{
if (![self ensureDatabaseOpen:error])
{
return;
}
NSLog(#">> ContactManager::updateContact");
// prep statement
sqlite3_stmt *statement;
NSString *querySQL = #"update contacts set name=?,address=?,phone=? where id=?";
NSLog(#"query: %#", querySQL);
const char *query_stmt = [querySQL UTF8String];
// preparing a query compiles the query so it can be re-used.
sqlite3_prepare_v2(_contactDb, query_stmt, -1, &statement, NULL);
sqlite3_bind_text(statement, 1, [[contact name] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 2, [[contact address] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 3, [[contact phone] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_int64(statement, 4, [[contact id] longLongValue]);
NSLog(#"bind name: %#", [contact name]);
NSLog(#"bind address: %#", [contact address]);
NSLog(#"bind phone: %#", [contact phone]);
NSLog(#"bind int64: %qi", [[contact id] longLongValue]);
// process result
if (sqlite3_step(statement) != SQLITE_DONE)
{
NSLog(#"error: %#", sqlite3_errmsg(_contactDb));
}
sqlite3_finalize(statement);
}

Related

Prepare-error : no such table: items

this function is showing me the error that "Prepare-error #0: no such table: items
". can some one please help me out in resolving this error.
- (void)viewDidLoad
{
[super viewDidLoad];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB)== SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"Select name FROM items"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{ NSLog(#"Data not fetched");
if (sqlite3_step(statement) == SQLITE_ROW)
{NSLog(#"Prepare-error #%i: %s", (sqlite3_prepare_v2(contactDB, [querySQL UTF8String], -1, &statement, NULL) == SQLITE_OK), sqlite3_errmsg(contactDB));
NSString *namefeild = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[list objectAtIndex:namefeild];
}
else{
NSLog(#"Data not fetched");
}
sqlite3_finalize(statement);
}else {NSLog(#"Prepare-error #%i: %s", (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK), sqlite3_errmsg(contactDB));}
sqlite3_close(contactDB);
}
These two functions are n different viewcontrollers.
In view didload the database is created.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPath;
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"contactDB"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath] == NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "create table if not exists items(name varchar, price integer, description varchar)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Fail to create table");
}
sqlite3_close(contactDB);
}else{
NSLog(#"Failed to open database");
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
and in save action the data is added to the database.
- (IBAction)save:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [ databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:#"insert into items(name, price, description) values (\"%#\",\"%#\",\"%#\")", nametxt.text, pricetxt.text, description.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"contact added");
nametxt.text= #"";
pricetxt.text = #"";
description.text = #"";
}else{
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
const char *dbpath = [databasePath UTF8String];
NSLog("%#", databasePath);
...
...
}
Copy the database path to your clipboard and paste it into your console.
cd "[database path]"
sqlite3 database_filename.db
.dump
After the .dump command, do you see the creation statement for your table? If not, then you need to double check the location of where you are actually creating your database. It would actually be very helpful if you updated your answer with the contents of the .dump command.
Typically this means that the table does not exist in the database you opened. You should find the database in your simulator's Documents folder (~/Library/Application Support/iPhone Simulator) and, open it in your MacOS SQLite tool of choice, see for yourself whether the table is there. I suspect it will not be there.
A common source of this problem is for a file at the databasePath to not exist (e.g. you might have copy of database in the bundle, but not the Documents folder), in which case sqlite3_open will quietly create a new, blank database at databasePath.
Assuming you don't want it to create a blank database when it doesn't find it, you should:
Remove your app from the simulator/device (so that any blank databases are removed);
Check your original opening routine and use NSFileManager to check for the existence of the database if it's not already there (perhaps copying the database from the bundle to documents before continuing);
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:databasePath]) {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"itemsdb" ofType:#"sqlite"];
[fileManager copyItemAtPath:bundlePath toPath:databasePath error:nil];
}
Or perhaps your code should dynamically create the table(s) if the database didn't exist, but the idea is the same. Check for existence of the file before opening it.
Perhaps in the future, consider using sqlite3_open_v2 with the SQLITE_OPEN_READWRITE option (but not the SQLITE_OPEN_CREATE option), which will not create the database for you and will report an error if the database was not found.
Having said the above (which is the general counsel when someone encounters an error like yours, where the table that you know "should" be there, isn't), there are specific issues unique to your code sample in the way you handle error reporting:
If step succeeds, you're reporting an error. Surely you meant to only do that if step failed.
The error you generate as a result of step says "prepare error". Surely that should be "step error".
Your logging of errors is calling the function that failed again in order to get the return code. You should save the return code when you first called the function, saving you from having to call it again for your error message. (This is important because sometimes the value returned by the function will change and reset your error message. Don't call the failed function again!) It's also more efficient to just save the original return code.
Thus:
if (sqlite3_open(dbpath, &contactDB)== SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"Select name FROM items"];
const char *query_stmt = [querySQL UTF8String];
int rc; // variable to hold the return code
if ((rc = sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL)) == SQLITE_OK)
{
if ((rc = sqlite3_step(statement)) == SQLITE_ROW)
{
NSString *namefeild = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[list objectAtIndex:namefeild];
}
else {
if (rc == SQLITE_DONE)
NSLog(#"step found no data");
else
NSLog(#"step-error #%i: %s", rc, sqlite3_errmsg(contactDB));
}
sqlite3_finalize(statement);
} else {
NSLog(#"Prepare-error #%i: %s", rc, sqlite3_errmsg(contactDB));
}
sqlite3_close(contactDB);
}

how to save the tabledata in sqlite in iphone

i am trying to store the data in table using sqlite manager.But the values are not stored in database.If i click the save button the error message will be displayed on like this Failed to open/create database. I cant understand how to solve the problem.Anybody please give me an idea how to solve this problem.Thanks in advance.
DBManager.m
-(BOOL)createDB {
NSString *docsDir;
NSArray *dirPaths;
// Get the document directory
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
docsDir=dirPaths[0];
// Build the path to the database file
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"Feedback.db"]];
BOOL isSuccess=YES;
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:databasePath]==0) {
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK) {
char *errMsg;
const char *sql_stmt= "create table if not exists Feeback details (Traineeid integer, Trainername text,Traineename text,Rating float)";
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;
}
// save data in the Database
-(BOOL) saveData:(NSString *)Traineeid Trainername:(NSString *)Trainername Traineename:(NSString *)Traineename Rating:(NSString *)Rating; {
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK) {
NSString *insertSQL=[NSString stringWithFormat:#"insert into Feedbackdetails(Traineeid,Trainername,Traineename,Rating) values(\"%d\",\"%#\", \"%#\", \"%#\")",[Traineeid integerValue],Trainername,Traineename,Rating];
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;
}
Ratingviewcontroller.m
-(IBAction)saveData:(id)sender {
BOOL success=NO;
NSString *alertString = #"Data Insertion failed";
if (Traineeid.text.length>0 &&Trainername.text.length>0 &&Traineename.text.length>0 &&Rating.text.length>0 ) {
success=[[DBManager getSharedInstance]saveData:Traineeid.text Trainername:Trainername.text Traineename:Traineename.text Rating:Rating.text];
}
else {
alertString = #"Enter all fields";
}
if (success == NO) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: alertString message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
You are not using the documents directory but the documentation directory. Use this NSDocumentsDirectory instead of NSDocumentationDirectory. Or even better, use the caches directory NSCachesDirectory because documents directory sync with iCloud and Apple might not like it since Documents directory should contain only user-downloaded files.

Getting error while executing SQLite command from application

I have this simple function in my application :
-(NSMutableArray *)SelectProductID:(NSMutableArray *)arr
{
NSLog(#"----------------");
sqlite3_stmt *statement;
NSMutableArray *arrPordID = [[NSMutableArray alloc]init];
#try
{
//Get productID
for(NSString *strSubProductID in arr)
{
NSString *s = [NSString stringWithFormat:#"SELECT ProductID FROM SubProducttable where SubProductID=%#",strSubProductID];
const char *sql = [s cStringUsingEncoding:NSASCIIStringEncoding];
if (sqlite3_prepare_v2(database, [s cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW){
char *dbString;
dbString = (char *)sqlite3_column_text(statement, 0);
NSString *pID = (dbString) ? [NSString stringWithUTF8String:dbString] : #"";
[arrPordID addObject:pID];
}
}
}
}
#catch (NSException *exception) {
#throw exception;
}
#finally {
sqlite3_finalize(statement);
}
return arrPordID;
}
I am encountering a strange problem here. When application reaches while (sqlite3_step(statement) == SQLITE_ROW){, loop is never entered. I don't know why. I executed the same query in SQLite manager (when application is not running). And I get result as a single one. The result I get is 2. But here I am getting nothing.
And yes, I always close the database in SQLite manager whenever I run my application. I have also cleaned the application, restarted XCode, and removed the application from simulator. But no success.
Also I saw a strange thing during debugging. While debugging, sqlite3_stmt *statement is always skipped. Is this the reason I am not getting any result?
Have you tried subproductId in single quotes?
NSString *s = [NSString stringWithFormat:#"SELECT ProductID FROM SubProducttable where SubProductID='%#'",strSubProductID];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlQuery = #"SELECT ProductID FROM SubProducttable where SubProductID=%#",strSubProductID;
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, statement, -1, &sqlQuery, NULL) == SQLITE_OK) {
while(sqlite3_step(sqlQuery ) == SQLITE_ROW) {
// Read the data and add to your array object
}
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
}
sqlite3_close(database)

how can I insert value into my sqlite3 database table?

I am writing a simple query as below
const char *sql = "insert into abc(name) values ('Royal')";
and this will insert each time 'Royal' into my 'name', so now I want to take input from user each time as names of hotel and wants to save them instead of 'Royal', so what should I do?
If you are not clear to my question, you may as me again,,,,,
this code is very simple for insert the value in sqlite3 table
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
database *objectDatabase=[[database alloc]init];
NSString *stringvalue2=[objectDatabase countValue];
[objectDatabase release];
NSLog(#"opened");
NSString *sql1;
sql1=[[NSString alloc] initWithFormat:#"insert into setting values('%i','%i','%i','%#','%i','%i','%#','%i','%i','%i','%i','%i','%i','%#');",intvalue1,
[[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
char *err1;
if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
{
NSLog(#"value inserted:");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Attention" message:#"You inserted successfully" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
}
[sql1 release];
sqlite3_close(myDatabase);
}
}
you need to connect to a database
- (sqlite3 *)database {
if (nil == db) {
NSString *path = <path to your database>;
int res = sqlite3_open([path UTF8String], &db);
if (res != SQLITE_OK){
// handle the error.
db = nil;
return nil;
}
}
return db;
}
then you can call this with the query
-(void)executeQuery:(NSString *)query{
sqlite3_stmt *statement;
if (sqlite3_prepare_v2([self database], [query UTF8String], -1, &statement, NULL) == SQLITE_OK) {
sqlite3_step(statement);
}else{
// handle the error.
}
sqlite3_finalize(statement);
}
-(void)dealloc {
//close database connection
sqlite3_close(db);
db = nil;
[super dealloc];
}
-(NSArray *) executeSelect:(NSString *)query {
//Data search block****************************************
char *zErrMsg;
char **result;
int nrow, ncol;
sqlite3_get_table(
[self database], /* An open database */
[query UTF8String], /* SQL to be executed */
&result, /* Result written to a char *[] that this points to */
&nrow, /* Number of result rows written here */
&ncol, /* Number of result columns written here */
&zErrMsg /* Error msg written here */
);
NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:3];
for (int i=0; i<nrow; i++){
[returnArray addObject:[NSString stringWithUTF8String:result[ncol + i]]];
}
sqlite3_free_table(result);
return returnArray;
}
Hi
if Your getting user inputs in userinput textfield
NSString *qry=[NSString stringwithformat:#"insert into abc(name) values (\"%#\")",userinput.text];
const char *sql = [qry UTF8string];
sqlite3 *contactDB;
const char *dbpath = [databasePath UTF8String]; // Convert NSString to UTF-8
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
{ // SQL statement execution succeeded
}
} else {
//Failed to open database
}

Assertion failure when trying to write (INSERT, UPDATE) to sqlite database on iPhone

I have a really frustrating error that I've spent hours looking at and cannot fix. I can get data from my db no problem with this code, but inserting or updating gives me these errors:
*** Assertion failure in +[Functions db_insert_answer:question_type:score:], /Volumes/Xcode/Kanji/Classes/Functions.m:129
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error inserting: db_insert_answer:question_type:score:'
Here is the code I'm using:
[Functions db_insert_answer:[[dict_question objectForKey:#"JISDec"] intValue] question_type:#"kanji_meaning" score:arc4random() % 100];
//update EF, Next_question, n here
[Functions db_update_EF:[dict_question objectForKey:#"question"] EF:EF];
To call these functions:
+(sqlite3_stmt *)db_query:(NSString *)queryText{
sqlite3 *database = [self get_db];
sqlite3_stmt *statement;
NSLog(queryText);
if (sqlite3_prepare_v2(database, [queryText UTF8String], -1, &statement, nil) == SQLITE_OK) {
} else {
NSLog(#"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
}
sqlite3_close(database);
return statement;
}
+(void)db_insert_answer:(int)obj_id question_type:(NSString *)question_type score:(int)score{
sqlite3 *database = [self get_db];
sqlite3_stmt *statement;
char *errorMsg;
char *update = "INSERT INTO Answers (obj_id, question_type, score, date) VALUES (?, ?, ?, DATE())";
if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) {
sqlite3_bind_int(statement, 1, obj_id);
sqlite3_bind_text(statement, 2, [question_type UTF8String], -1, NULL);
sqlite3_bind_int(statement, 3, score);
}
if (sqlite3_step(statement) != SQLITE_DONE){
NSAssert1(0, #"Error inserting: %s", errorMsg);
}
sqlite3_finalize(statement);
sqlite3_close(database);
NSLog(#"Answer saved");
}
+(void)db_update_EF:(NSString *)kanji EF:(int)EF{
sqlite3 *database = [self get_db];
sqlite3_stmt *statement;
//NSLog(queryText);
char *errorMsg;
char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = '?'";
if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == SQLITE_OK) {
sqlite3_bind_int(statement, 1, EF);
sqlite3_bind_text(statement, 2, [kanji UTF8String], -1, NULL);
} else {
NSLog(#"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
}
if (sqlite3_step(statement) != SQLITE_DONE){
NSAssert1(0, #"Error updating: %s", errorMsg);
}
sqlite3_finalize(statement);
sqlite3_close(database);
NSLog(#"Update saved");
}
+(sqlite3 *)get_db{
sqlite3 *database;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *copyFrom = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"/kanji_training.sqlite"];
if([fileManager fileExistsAtPath:[self dataFilePath]]) {
//NSLog(#"DB FILE ALREADY EXISTS");
} else {
[fileManager copyItemAtPath:copyFrom toPath:[self dataFilePath] error:nil];
NSLog(#"COPIED DB TO DOCUMENTS BECAUSE IT DIDNT EXIST: NEW INSTALL");
}
if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database); NSAssert(0, #"Failed to open database");
NSLog(#"FAILED TO OPEN DB");
} else {
if([fileManager fileExistsAtPath:[self dataFilePath]]) {
//NSLog(#"DB PATH:");
//NSLog([self dataFilePath]);
}
}
return database;
}
+ (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"kanji_training.sqlite"];
}
I really can't work it out! Can anyone help me?
Many thanks.
in db_insert_answer, you prepare your statement
if the prepare is SQLITE_OK, you bind your variables
however, regardless of preparation OK or not, you run the statement (which could be invalid)
you also do the same thing in db_update_EF
start there
char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = '?'";
Replace it with
char *update = "UPDATE Kanji SET EF = ? WHERE Kanji = ?";
It's already a string. You don't need single quotes around that question mark.