I'm trying to insert some data in a SQLite 3 database in an iOS app. But i keep getting an error that is useless to me.
This is my code trying to insert:
#try {
NSString *dbPath = [self.GetDocumentDirectory stringByAppendingPathComponent:#"knhb.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if((sqlite3_open_v2([dbPath UTF8String], &db, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK))
{
NSLog(#"An error has occured.");
}
NSString *sqlString = [NSString stringWithFormat:#"INSERT INTO Profile (name, password) VALUES ('%#','%#')", name, password];
const char *sql = [sqlString UTF8String];
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, 1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"%s SQLITE_ERROR '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(db), sqlite3_errcode(db));
}
sqlite3_step(sqlStatement);
sqlite3_finalize(sqlStatement);
int lastInsert = sqlite3_last_insert_rowid(db);
NSLog(#"lastinsertid:%d", lastInsert);
sqlite3_close(db);
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
My database table Profile has three columns idProfile, name and password. But since idProfile is an int and primary key I don't have to include it because it is auto incremented.
The error I keep getting is: SQLITE_ERROR 'near "I": syntax error' (1)
I am writing to the Documents folder.
Any help is greatly appreciated.
Daan
I'm not quite sure why but i fixed it by changing the following line of code:
if(sqlite3_prepare_v2(db, sql, 1, &sqlStatement, NULL) != SQLITE_OK)
i've turned it into:
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
Not sure what the 1 or -1 means. Maybe someone can elaborate?
Cheers!
Related
Code:
#try {
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char * sql="Select Id, Name,Designation, Skill, Credits, Selected from candidate_info where Designation like '%%%#%%'";
if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [searchWord UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) ==SQLITE_ROW)
{
}
}
else
NSAssert1(0, #"Error in candidateinfo. '%s'", sqlite3_errmsg(database));
sqlite3_reset(statement);
}
}#catch (NSException * e) {
NSLog(#"Exception is %#, %#", [e name], [e reason]);
}#finally {
sqlite3_finalize(statement);
sqlite3_close(database);
}
I try to fetch data from sqlite based on search keyword.I tried with like statement.The query is not executing and is goes out of while loop.what is wrong with my code.thanks in advance
Try creating your Query using NSString :
NSString *sql = [NSString stringWithFormat:#"Select Id, Name,Designation, Skill, Credits, Selected from candidate_info where Designation like '%#'", searchWord] ;
if (sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK)
{
}
Problem is that you are using 'sqlite3_bind_text' in wrong way.
Your query must be :
const char * sql="Select Id, Name,Designation, Skill, Credits, Selected from candidate_info where Designation like '%%?%%'";
You are missing '?'
I found answer to my question
NSString *query = [NSString stringWithFormat:#"Select Id, Name,Designation, Skill, Credits, Selected from candidate_info where Designation LIKE '%%%#%%'", searchWord];
const char *sql = [query UTF8String];
Using For in loop inserting or updating table using SQlite query ,it's throw updating correctly message and also Error while updating. 'unknown error' error msg also.Insertion is done correctly but update not worked same if run update query in SQLite Manager it worked..thanks advance
sqlite3 *database;
NSString * databaseName=[[NSString alloc]initWithString:DBName];
NSArray * documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString * databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
NSString *lite;
BOOL check=[self isContainsID:filename];
if(check)
{
lite=[NSString stringWithFormat:#"INSERT INTO table_name(id,filename,date)VALUES('%#',%d,'%#')",id,filename,date];
}
else
{
lite=[NSString stringWithFormat:#"UPDATE table_name SET date='%#' where filename ='%#'",date,filename];
const char *sqlStatement = [lite UTF8String];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement=nil;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) != SQLITE_OK)
{
if(Debug)
{
DLog(#"not updated");
DLog(#"HMM, COULDNT RUN QUERY: %s\n", sqlite3_errmsg(database));
}
}
else
{
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(#"updated successfully");
}
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
[databaseName release];
[databasePath release];
This code is wrong and results in calling sqlite3_step() twice:
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(#"updated successfully");
}
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
I'm sure you meant:
if (sqlite3_step(compiledStatement) == SQLITE_DONE)
{
DLog(#"updated successfully");
}
else
{
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
}
Also you should be binding your statement variable instead of formatting them into the statement with [NSString stringWithFormat:], as it's both more secure and allows the statements to be re-used (which is the point of preparing them).
Help, not working UPDATE in SQite. query is executed but the changes do not occur
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath, &contactDB)==SQLITE_OK) {
NSLog(#"database Opened");
const char* updateQuery="update poi set test=\"111\"";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(contactDB, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
NSLog(#"Query Executed");
}
}
sqlite3_close(contactDB);
you made minor mistake....
Write ur stuff in following template, you missed the main execution statement i.e.
sqlite3_step(statement);
What is happening here, you are just preparing the statement and not executing it..
sqlite3_stmt *statement;
if(sqlite3_open(dbpath, &database_object) == SQLITE_OK)
{
NSString *sql = [NSString stringWithFormat:#"update table_name set column_name = \"%#\"", Your_value];
const char *sql_stmt = [sql UTF8String];
if(sqlite3_prepare_v2(database_object , sql_stmt, -1, &statement, NULL) != SQLITE_OK)
NSLog(#"Error while creating update statement. '%s'", sqlite3_errmsg(database_object));
if(SQLITE_DONE != sqlite3_step(statement))
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database_object));
sqlite3_finalize(statement);
}
Make these changes in your code and try, i think it will work...
You haven't executing the Query :
sqlite3_prepare_v2- Just prepared not to execute(affect) , You need to execute it
Try this Out:
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath, &contactDB)==SQLITE_OK) {
NSLog(#"database Opened");
const char* updateQuery="update poi set test=\"111\"";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(contactDB, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
NSLog(#"Query Prepared to execute");
}
if(sqlite3_step(stmt) != SQLITE_DONE){
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
}else
NSLog(#"Executed");
sqlite3_close(contactDB);
}
I have sqlite database in iPhone app and there I store questions.
I get one question, user answers YES or NO, result is showing on second viewController and when second viewController is closing I get another question.
Everything works perfectly and suddenly after 30-40 questions, program cannot open database.
if(sqlite3_open([DBPath UTF8String], &database) == SQLITE_OK) - it fails.
Any answers?
This function:
// get Question from Database
- (void)getQuestion:(int)getQ
{
NSLog(#"getQuestion Started");
sqlite3 *database;
sqlite3_stmt *compiledStatement = NULL;
if(sqlite3_open([DBPath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"sqlite opened");
const char *sql = "Select QuestionID, Question from cQuestions WHERE ExerciseLinID = ? ORDER BY QuestionID LIMIT ?, 1";
if(sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating detail view statement. '%s'", sqlite3_errmsg(database));
int curExID = [[listOfExID objectAtIndex:ExSel] integerValue];
sqlite3_bind_int(compiledStatement, 1, curExID);
sqlite3_bind_int(compiledStatement, 2, getQ);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
{
NSLog(#"Got one record");
selectedQues = sqlite3_column_int(compiledStatement, 0);
NSLog(#"selectedQues = %i", selectedQues);
const char *QuNam = (char *)sqlite3_column_text(compiledStatement, 1);
if(QuNam == nil)
NSLog(#"!!! No data found.");
else
{
if( iWhat == YES )
_labQuestion.text = [[NSString alloc] initWithCString:QuNam encoding:NSASCIIStringEncoding];
else
_labQuestionPad.text = [[NSString alloc] initWithCString:QuNam encoding:NSASCIIStringEncoding];
}
}
}
else
{
NSLog(#"!!! Open error. %s", sqlite3_errmsg(database));
NSLog(#"!!! Open error. %d", sqlite3_errcode(database));
}
sqlite3_close(database);
}
Add some NSLog to understand which is the error.
if(sqlite3_open([DBPath UTF8String], &database) == SQLITE_OK) {
// Your Code
}
else {
NSLog(#"sqlite3_open failed. Error:%d. %s", sqlite3_errcode(database), sqlite3_errmsg(database));
}
One potential problem is the fact that you aren't closing your database, are you closing it?
sqlite3_close(database);
I am trying to update one of my table's column upon button click.
The issue is that code isn't giving any exception still it is not updating the table.
When the view controller load again , it shows the old value rather then updated one.
Code for update db is attached below.
#try {
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *sqlStatement = #"UPDATE messagesTable SET Favorite = 1 where MessageID=";
sqlStatement = [sqlStatement stringByAppendingString:msgId];
NSLog(#"sql statement: %#", sqlStatement);
const char *sql = [sqlStatement UTF8String];
int result = sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL);
if(result != SQLITE_OK) {
NSLog(#"Prepare-error #%i: %s", result, sqlite3_errmsg(database));
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
#catch (NSException *exception) {
NSLog(#"Name: %#",exception.name);
NSLog(#"Reason: %#",exception.reason);
}
#finally {
}
Any suggestions are welcome. :-)
You are not calling sqlite3_step, which performs the update. After the sqlite3_prepare and before the sqlite3_finalize, you need something like:
if (sqlite3_step(compiledStatement) != SQLITE_DONE)
NSLog(#"%s: step error: %s", __FUNCTION__, sqlite3_errmsg(database));