iPhoneSdk, SQLite database search query not work - iphone

i want to know how to pass particular word or character in search query to find records..
i am passing in the format like '%%%#%%'.
but it doesn't give me output...
this is my code...
searchName = [NSString stringWithFormat:#"'%%%#%%'",[[NSUserDefaults standardUserDefaults] objectForKey:#"key"]];
-(void)getSearchData
{
NSLog(#"search Name %#", searchName);
searchArray = [[NSMutableArray alloc] init];
const char *sql = "select * from features where lower(name) like ? limit 500";
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL)!= SQLITE_OK)
{
NSAssert1(0,#"error : failed to prepare statement with message '%s'.",sql ite3_errmsg(database));
}
sqlite3_bind_text(selectstmt, 1, [searchName UTF8String], -1, SQLITE_TRANSIENT);
// sqlite3_bind_text(selectstmt, 2, [state UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSMutableDictionary *datah = [[NSMutableDictionary alloc] init];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,0)] forKey:#"number"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,1)] forKey:#"name"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,2)] forKey:#"type"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,4)] forKey:#"country"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,5)] forKey:#"lat"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,6)] forKey:#"long"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,7)] forKey:#"elevation"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,8)] forKey:#"area"];
[datah setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,3)] forKey:#"state"];
[searchArray addObject:datah];
[datah release];
}
sqlite3_reset(selectstmt);
}
if i pass a same query with word "s" i got 100 of record in sqlite query builder but if m pass through above code it doesn't serach any record
please help me

I worked on the code given above and fixed it as follows
-(void)getSearchData:(NSString*)searchText
{
**NSString* searchName = [NSString stringWithFormat:#"%%%#%%",searchText];**
NSLog(#"search Name %#", searchName);
sqlite3 *database;
sqlite3_stmt *selectstmt;
NSString* searchQuery = #"SELECT * FROM contacts WHERE lower(name) like ?";
const char *sql = [searchQuery UTF8String];
**if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {**
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) != SQLITE_OK)
{
//NSAssert1(0,#"error : failed to prepare statement with message '%s'.",sql ite3_errmsg(database));
}
sqlite3_bind_text(selectstmt, 1, [searchName UTF8String], -1, SQLITE_STATIC);
while (sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,0)]);
}
sqlite3_reset(selectstmt);
}
sqlite3_close(database);
}
The changed portions can be found between Double *. you would also like to read this
Two steps that I changed were opening the database connection which You must have done elsewhere and second removing the '' from searchName. Do let us know if this resolves the issue.

Related

Passing variable in query does not show any result

I have table in sqlite I want to get data where userNAme and organizatiocode. problem is that it does not show any rows. If I do not pass variable and select all data then it returns rows.
Here is my code
+(void)getInitialData:(NSString *)dbPath {
MultipleDetailViewsWithNavigatorAppDelegate *appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSLog(#"User NAme is %#",appDelegate.userName);
// const char *sql = "select * from library";
const char *sql = "select * from library where userName=?";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
//sqlite3_bind_text(selectStmt, 1, [appDelegate.userName UTF8String], -1, SQLITE_TRANSIENT);
//sqlite3_bind_text(selectStmt, 1, [appDelegate.organizationCode UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(selectStmt , 1, [appDelegate.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(selectStmt , 2, [appDelegate.organizationCode UTF8String], -1, SQLITE_TRANSIENT);
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.userID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
coffeeObj.contentAddedDateTime = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,2)];
coffeeObj.contentType = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,3)];
coffeeObj.contentTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,4)];
coffeeObj.contentSource = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,5)];
coffeeObj.contentDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,6)];
coffeeObj.categoryTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,7)];
coffeeObj.subCategoryTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,8)];
coffeeObj.organizationCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,9)];
coffeeObj.userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,10)];
int count=[appDelegate.libraryArrayLocal count];
NSLog(#"count is beofore getting values %d",count);
[appDelegate.libraryArrayLocal addObject:coffeeObj];
int countone=[appDelegate.libraryArrayLocal count];
NSLog(#"count is after getting values %d",countone);
[coffeeObj release];
}
}
}
else
sqlite3_close(database);
}
}
Try to use:
NSString *query = [NSString stringWithFormat:#"select * from library where userName=%#",appDelegate.userName];
const char *sql = [query UTF8String];
Instead of:
const char *sql = "select * from library where userName=?";
also try without binding,
if(sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//do your stuff here
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

sqlite3_prepare_v2 statement is not SQLITE_OK and I don't know why

I have this code in my viewWillAppear method:
sqlite3 *database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, #"Failed to open database");
}
sqlite3_stmt *statement;
//why is this if statement failing?
if (sqlite3_prepare_v2(database, [sqlStatement UTF8String],
-1, &statement, nil) == SQLITE_OK) {
It passes the first if statement without entering (which is good). The 2nd if statement is the problem.
The sqlStatement is in the form of SELECT * FROM food WHERE foodType = 'fruit'
I don't understand why it's not getting into the if statement. Any help would be appreciated.
The problem ended up not being in the code, but in the way that I exported the sqlite file. It was a series on INSERT statements, not an actual table.
and make changes according to ur requirement...
-(void) readDataFromDatabase
{
chapterAry = [[NSMutableArray alloc] init];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:#"QuotesApp.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement ="select * from MsExcelTutorial";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiledStatement)==SQLITE_ROW)
{
NSNumber *chapterId = [NSNumber numberWithInt:(int)sqlite3_column_int(compiledStatement, 0)];
NSString *chapter = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *link = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *bookmark = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:chapterId,#"chapterId",chapter,#"chapter",link,#"link",bookmark,#"bookmark", nil];
[chapterAry addObject:dic];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
NSString *DBPath = [ClsCommonFunctions GetDatabasePath];
if ([self OpenDBWithPath:DBPath])//Method to open database connection
{
//filesDB is database object
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select fileID,filePath from tblFiles where isUploadPending =1";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(filesDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// u Need to get data from database...
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
sqlite3_close(filesDB);
}
go through it it will work

Sqlite data not getting fetching

I am trying fetch the value from data base But it is not getting
I am trying this code but didn't get the value ,When i use the Break point on the program
I am having Longitude,Latitude his data type is double in data base
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from Location"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
NSLog(#"%i",i); **//over here i am getting the 101 value in console** And my pointer getting out from here
NSString *dLongitude = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *dLatitude = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
[locations addObject:[NSString stringWithFormat:#"%# ,%#",dLongitude,dLatitude]];
NSLog(#"%#",locations);
}
result = [locations componentsJoinedByString:#" "]; // same as `fake_location`
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
NSLog(#"%i",i); **//over here i am getting the 101 value in console** And my pointer getting out from here
double longitude = sqlite3_column_double(compiledStatement, 3);
double latitude = sqlite3_column_double(compiledStatement, 4);
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f",longitude,latitude] autorelease];
[locations addObject:coords];
NSLog(#"%#",locations);
}
Change the code to the following :
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from UserJourneyLocation"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
// NSLog(#"%i",i); / comment this line or use NSLog(#"%d",i);
// Make sure your longitude is double in database. else change the fetching value declaration
// We use 0 for dLongitude instead of 3 because in the select statement, it is the first value to be fetched irrespective of your table structure
// and same for dLatitude.
double dLongitude = sqlite3_column_double(compiledStatement, 0);
double dLatitude = sqlite3_column_double(compiledStatement, 1);
[locations addObject:[NSString stringWithFormat:#"%d ,%d",dLongitude,dLatitude]];
NSLog(#"%#",locations);
}
result = [locations componentsJoinedByString:#" "]; // same as `fake_location`
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

Accessing an object through SQLIte database

I am passing an object to the method in which I am executing a query. My method is:
-(BOOL)searchWordInDatabase:(NSString *)string
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalkLanguageElement.sqlite"];
//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
const char *sql="select ImageName from tblLanguageElement where Category= string";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}
}
return NO;
}
But I am not getting the value of the String in the query. How can I do it?
There is a mistake in your query. You can not substitute a string like that. Do it in the following way.
NSString *sqlStr = [NSString stringWithFormat:#"select ImageName from tblLanguageElement where Category = '%#'", string];
char *sql = (char *)[sqlStr UTF8String];
Make sure that your database exists at that path you retrieve. And you can bind string variables as follows while executing statements.
const char *sql = "select ImageName from tblLanguageElement where Category = ?";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}

Problem With Sqlite Data Retrieving

I have an SQLite database, and when I am trying to get the data from the database, I get the last inserted element repeatedly. How can I get all the elements with no repetition.
The code I've written:
- (NSMutableArray *) gettingData {
sqlDict = [[NSMutableDictionary alloc] init];
membersInfoArray =[[NSMutableArray alloc]init ];
[self checkAndCreateDatabase];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from ProductList";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *prdbcode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
[sqlDict setObject:prdbcode forKey:#"Barcode"];
[prdbcode release];
NSString *prdname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
[sqlDict setObject:prdname forKey:#"ProductName"];
[prdname release];
NSString *prdDesc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
[sqlDict setObject:prdDesc forKey:#"ProductDescription"];
[prdDesc release];
NSString *prdstatus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
[sqlDict setObject:prdstatus forKey:#"ProductStatus"];
[prdstatus release];
[membersInfoArray addObject:sqlDict];
[sqlDict release];
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return membersInfoArray;
}
I am retrieving the data as follows:
NSMutableArray *sqlArray = [sqlViewController gettingData];
Thank you.
Just Declare your array globally instead of declare locally in your method. Your problem will resolved.