Comparing integers in sqlite table? - ios

I have a high scores table in my game. When the game is over, the score is shown on the screen and it gets inserted into the high scores table. I want to know how to compare the new score to the highest score in the table so I can let the user know if they achieved a high score. Below I included the code I use to update and insert the score into the table. The score being kept is an integer, globalScore.
-(void)updateScores:(NSInteger)Primary_key
{
sqlite3_stmt *statement=nil;
NSString *sql=nil;
#try
{
statement=nil;
sql=nil;
sql=[NSString stringWithFormat:#"update tblHard set Score=? where id=%d",Primary_key];
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_int(statement, 1, globalScore);
int success=sqlite3_step(statement);
if (success == SQLITE_ERROR) {
NSAssert1(0, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
statement=nil;
sql=nil;
}
#catch (NSException *e)
{
NSLog(#"asd");
}
}
-(int)InsertGame
{
int i=0;
sqlite3_stmt *statement=nil;
NSString *sql=nil;
#try
{
statement=nil;
sql=nil;
sql=[NSString stringWithFormat:#"insert into tblHard(Score) values (?)"];
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL)!=SQLITE_OK)
{
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_int(statement, 1, globalScore);
int success=sqlite3_step(statement);
if (success == SQLITE_ERROR) {
NSAssert1(0, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
}
i= sqlite3_last_insert_rowid(database);
sqlite3_finalize(statement);
statement=nil;
sql=nil;
}
#catch (NSException *e)
{
NSLog(#"asd");
}
return i;
}
So what I'm looking for is something like this...
if(globalScore > "the highest score in the table"){
highscorelabel.hidden=NO;
}

You can retrieve the highest score in the table with
select max(Score) from tblHard
You can retrieve the result of this SQL query with sqlite3_column_int. Here is the code (error checking removed for brevity):
int highestScore;
/* ... */
sqlite3_prepare_v2(database, "select max(Score) from tblHard", -1,
&statement, NULL);
sqlite3_step(statement);
highestScore = sqlite3_column_int(statement, 0);
And then you can compare the current maximum score with globalScore:
if (globalScore > highestScore) {
/* ... */
}

Related

iOS How to form sqlite like statement?

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];

getting error in sqlite Update in ios

i am getting error in the sqlite updation,here the query is correctly given, but the value is not updating.here i need to update the description value Where the given place, Below i add my code please help me
-(void) update:(NSString *)filePath withName:(NSString *)place description:(NSString*)description
{
sqlite3* db = NULL;
int rc=0;
sqlite3_stmt* stmt =NULL;
rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE , NULL);
if (SQLITE_OK != rc)
{
sqlite3_close(db);
NSLog(#"Failed to open db connection");
}
else
{
NSString * query = [NSString stringWithFormat:#"UPDATE places SET description=%# WHERE place=%#",description,place];
sqlite3_bind_text(stmt, 1, [place UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, [description UTF8String], -1, SQLITE_TRANSIENT);
NSLog(#"query %#",query);
char * errMsg;
rc = sqlite3_exec(db, [query UTF8String] ,NULL,&stmt,&errMsg);
if(SQLITE_OK != rc)
{
NSLog(#"Failed to insert record rc:%d, msg=%s",rc,errMsg);
}
else{
NSLog(#"Sucessfully updated");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
}
}
Table Creation
-(int) createTable:(NSString*) filePath
{
sqlite3* db = NULL;
int rc=0;
NSLog(#"create");
rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (SQLITE_OK != rc)
{
sqlite3_close(db);
NSLog(#"Failed to open db connection");
}
else
{
char * query ="CREATE TABLE IF NOT EXISTS places ( id INTEGER PRIMARY KEY AUTOINCREMENT,place TEXT ,locationname TEXT,time TEXT,description TEXT,notifyTime TEXT,radius TEXT,lat DOUBLE,lon DOUBLE ,notify TEXT,selection INTEGER)";
char * errMsg;
rc = sqlite3_exec(db, query,NULL,NULL,&errMsg);
if(SQLITE_OK != rc)
{
NSLog(#"Failed to create table rc:%d, msg=%s",rc,errMsg);
}
else{
NSLog(#"Sucessfully Created ");
}
sqlite3_close(db);
}
return rc;
}
First open the DB connection.
Then write below code.
NSString * query = [NSString stringWithFormat:#"UPDATE places SET description=%# WHERE place=%#",description,place];
SQL=[NSString stringWithString:query];
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int result=sqlite3_step(insert_statement);
sqlite3_finalize(insert_statement);
and then close the DB connection
try this ...check db is whether it is opened or not and change this code...
-(void) update:(NSString *)filePath withName:(NSString *)place description:(NSString*)description
{
sqlite3* db = NULL;
int rc=0;
sqlite3_stmt* stmt =NULL;
rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE , NULL);
if (SQLITE_OK != rc)
{
sqlite3_close(db);
NSLog(#"Failed to open db connection");
}
else
{
/*
NSString *strMQueryupdate=[NSString stringWithFormat:#"update br set TOTAL='%#',QUTY='%#' WHERE PID='%#'",[#(total )stringValue],[#(lblQtn )stringValue],produdId];
*/
NSString * query = [NSString stringWithFormat:#"UPDATE places SET description='%#' WHERE place='%#'",description,place];
const char *sql = [query UTF8String];
if (sqlite3_prepare_v2(db, sql, -1, & stmt, NULL) != SQLITE_OK)
{
NSLog(#"update fails");
}
else
{
sqlite3_bind_text(stmt, 1, [place UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, [description UTF8String], -1, SQLITE_TRANSIENT);
int success = sqlite3_step(stmt);
sqlite3_reset(stmt);
if (success == SQLITE_ERROR)
{
}
else
{
NSLog(#"update success");
}
sqlite3_finalize(update_statement);
sqlite3_close(db);
}
}
You're using prepared statements incorrectly. You hard-code the values in a string (a bad idea) and then setting the placeholder values -- which makes no sense as there are no placeholders in your SQL. Try something like:
NSString * query = #"UPDATE places SET description= ? WHERE place= ?";
sqlite3_bind_text(stmt, 1, [place UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, [description UTF8String], -1, SQLITE_TRANSIENT);
The reason you don't want to include the values directly in the query string: imagine someone passing in a value for place like "London'; drop table places;". (Not sure if that'll work but it should give you some idea of the kind of mischief that a user could get up to.)

sqlite many opens one fail

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);

Sqlite3 update query not working in ios app

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));

Error during insert statement with SQLite3 in iOS

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!

Resources