How to fetch All data of the columns in the table - iphone

this is my code...
i want to fetch all the quotes data that have 320 quote but it only fetch the first one quote. please help me
-(NSMutableArray *)getAllQuotesData
{
NSMutableArray *quotesArray = [[NSMutableArray alloc] init];
NSString *sqlStr = [NSString stringWithFormat:#"SELECT quote FROM quotes"];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement:sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
QuotesDC *myQuote = [[QuotesDC alloc] init];
NSString *user_id = [NSString stringWithUTF8String:(char
*)sqlite3_column_text(ReturnStatement,0)];
NSString *category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,1)];
NSString *subcategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,2)];
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,0)];
NSString *star = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,4)];
myQuote.userid = [user_id integerValue];
myQuote.category = category;
myQuote.subcategory = subcategory;
myQuote.quote = quote;
myQuote.star = star;
[quotesArray addObject:myQuote];
NSLog(#"%u", quotesArray.count);
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
return quotesArray;
}
}

nothing wrong with your code just do one thing return dataArray will be outside of the loop , you will load all quotes like this, accept my answer thanks
-(NSMutableArray *)getAllQuotesData
{
NSMutableArray *quotesArray = [[NSMutableArray alloc] init];
NSString *sqlStr = [NSString stringWithFormat:#"SELECT quote FROM quotes"];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement:sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
QuotesDC *myQuote = [[QuotesDC alloc] init];
NSString *user_id = [NSString stringWithUTF8String:(char
*)sqlite3_column_text(ReturnStatement,0)];
NSString *category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,1)];
NSString *subcategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,2)];
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,0)];
NSString *star = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,4)];
myQuote.userid = [user_id integerValue];
myQuote.category = category;
myQuote.subcategory = subcategory;
myQuote.quote = quote;
myQuote.star = star;
[quotesArray addObject:myQuote];
NSLog(#"%u", quotesArray.count);
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
}
return quotesArray;
}

Replace your query string with this
NSString *sqlStr = [NSString stringWithFormat:#"SELECT * FROM quotes WHERE quote=320"];

Use this code,this may help you
-(void)retrivequoteFromDB
{
NSMutableArray * quoteArray=[[NSMutableArray alloc]init];
sqlite3 *sqliteDB;
sqlite3_stmt *compiledStatement = NULL;
if(sqlite3_open([databasePath UTF8String], &sqliteDB)==SQLITE_OK)
{
NSString *sql=#"SELECT quote FROM quotes";
const char *sqlC=[sql UTF8String];
if(sqlite3_prepare(sqliteDB, sqlC, -1, &compiledStatement, NULL)==SQLITE_OK)
{
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
[quoteArray addObject:quote];
}
}
sqlite3_reset(compiledStatement);
}
sqlite3_finalize(compiledStatement);
}

try like this once check your data base table 320 records placed or not if present then it'l gives ll the data.
SELECT quote FROM quotes //it'l gives only quote columnvalues from quotes table.
if you want to get all the data then use asterisk '*' symbol in the place of quote.
otherwise try like this,
SELECT quote FROM quotes limit 320 //it'l gives top 320 records
once read this one you'l found the problem. select Query

Related

Arabic string in NSMutableArray or NSMutableDictionary

I have a problem when I add an arabic string to NSMutableArray or NSMutableDictionary.
Example:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"%#",data);
Output:
2012-01-18 21:55:05.646 aa[367:207] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
my problem exactly i save this data to sqlite [data objectForKey:#"name"] its saved \U0641\U0631\U0633\U0627\U0646 and when fetch data to to put it in UILabel or anything like it the text be \U0641\U0631\U0633\U0627\U0646
Any Help? Thank you :)
- (void)SaveMessage {
NSMutableDictionary *TableProperties = [[NSMutableDictionary alloc]init];
[TableProperties setObject:#"INSERT" forKey:#"Operation"];
[TableProperties setObject:#"savedmessages" forKey:#"tableName"];
NSString *string = [[NSString alloc]initWithFormat:#" %#",MessageBox.text];
[TableProperties setValue:string forKey:#"message"];
NSString *msgResult;
NSArray *result = [[DatabaseFunctions database] DataBaseOperation:TableProperties];
if ([[result objectAtIndex:0] isEqualToString:#"Done"])
msgResult = #"تم حفظ الرسالة بنجاح";
else
msgResult = #"لم تت العملية بنجاح حاول لاحقا";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"حفظ الرسالة"
message:msgResult
delegate:self
cancelButtonTitle:#"موافق"
otherButtonTitles:nil, nil ];
[alert show];
}
- (NSArray *)DataBaseOperation:(NSMutableDictionary *)TableProperties{
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *Operation = [TableProperties objectForKey:#"Operation"];
if ([Operation isEqualToString:#"SELECT" ]) {
NSString *tableColumns = [TableProperties objectForKey:#"tableColumns"];
NSString *tableName = [TableProperties objectForKey:#"tableName"];
NSString *tableWhere = [TableProperties objectForKey:#"tableWhere"];
NSString *tableOrder = [TableProperties objectForKey:#"tableOrder"];
NSString *tableLimit = [TableProperties objectForKey:#"tableLimit"];
NSString *Query;
if ([tableLimit isEqualToString:#"NO"]) {
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}else{
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %# LIMIT %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}
NSArray *FieldArray = [[TableProperties objectForKey:#"tableColumns"] componentsSeparatedByString:#","];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *Row = [[NSMutableDictionary alloc]init];
NSString *uniqueId = [[NSString alloc] initWithFormat:#"%i",sqlite3_column_int(statement, 0)];
[Row setObject:uniqueId forKey:#"uniqueId"];
for (int i = 1; i<[FieldArray count]; i++) {
NSString *column = [[NSString alloc] initWithUTF8String:(char *) sqlite3_column_text(statement, i)];
[Row setObject:column forKey:[FieldArray objectAtIndex:i]];
}
Objects *rowOfTable = [[Objects alloc] initSelectDataFromTables:Row];
Row = nil;
[retval addObject:rowOfTable];
}
sqlite3_finalize(statement);
}
}
else if([Operation isEqualToString:#"INSERT" ]) {
NSString *tableName = [TableProperties objectForKey:#"tableName"];
[TableProperties removeObjectForKey:#"Operation"];
[TableProperties removeObjectForKey:#"tableName"];
NSArray *Columns = [TableProperties allKeys];
NSArray *Values = [TableProperties allValues];
NSString *Query = [[NSString alloc] initWithFormat:#"INSERT INTO %# %# VALUES %#",tableName,Columns,Values];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK)
if (SQLITE_DONE!=sqlite3_step(statement)){
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}else{
NSLog(#"Data inserted Successfully");
[retval addObject:#"Done"];
}
else{
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}
sqlite3_finalize(statement);
}
return retval;
}
When you log an object using %#, NSLog sends the description message to the object and prints the resulting string.
An NSDictionary responds to the description message by encoding its keys and values in a "safe" format, escaping non-ASCII characters using \U#### codes.
If you pass the Arabic string to NSLog directly, it will just print the string without the escape codes:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"data = %#",data);
NSLog(#"string = %#", [data objectForKey:#"name"]);
Output:
2012-01-18 14:17:42.498 Animal[62723:f803] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
2012-01-18 14:17:42.500 Animal[62723:f803] فرسان
If you don't like the way NSDictionary responds to description, you will have to write your own method to format a dictionary as a string and use it to log your dictionary.
Update
I have looked at the source code you posted that talks to sqlite. The problem is that you are turning the values array ([TableProperties allValues]) into a string using the %# format specifier. This sends the description method to the NSArray, which returns a string. Just like NSDictionary, NSArray formats the description string in a "safe" format, escaping non-ASCII characters using \U#### codes.
You need to write your own method that takes an array and turns it into a string and does not escape special characters. (It needs to escape quotes though.)

Problem with SQLITE SELECT IN for multiple parameters in iPhone

I have a method, which generates a dictionary of returned values from database:
- (NSDictionary *)getParametersForPreset:(NSUInteger)presetID plants:(NSArray *)plants
{
NSString *loggers = #"";
NSString *invertors = #"";
NSString *plantsList = #"";
const char *sql = "SELECT loggerID, invertorID FROM records WHERE presetID IN (?) AND plantID IN (?)";
BOOL isEmpty = YES;
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(#"Error: '%s'.", sqlite3_errmsg(database));
}
for (int i = 0; i < [plants count]; i++) {
if (i == 0)
{
plantsList = [NSString stringWithFormat:#"'%#'",[[plants objectAtIndex:0] valueForKey:#"id"]];
}
else
{
plantsList = [plantsList stringByAppendingFormat:#",'%#'",[[plants objectAtIndex:i] valueForKey:#"id"]];
}
}
NSLog(#"plants: %#", plantsList);
NSLog(#"preset: %d", presetID);
sqlite3_bind_int(statement, 1, presetID);
sqlite3_bind_text(statement, 2, [plantsList UTF8String], -1, SQLITE_TRANSIENT);
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
int i = 0;
while (sqlite3_step(statement) == SQLITE_ROW)
{
if (i == 0)
{
loggers = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
invertors = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
isEmpty = NO;
i++;
}
else
{
loggers = [loggers stringByAppendingFormat:#",%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
invertors = [invertors stringByAppendingFormat:#",%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)]];
}
}
sqlite3_reset(statement);
if (isEmpty == YES)
{
return nil;
}
[dictionary setValue:[NSString stringWithString:[plantsList stringByReplacingOccurrencesOfString:#"'" withString:#""]] forKey:#"plants"];
[dictionary setValue:loggers forKey:#"loggers"];
[dictionary setValue:invertors forKey:#"invertors"];
return dictionary;
}
This query returns me nothing in the code, but then I do the same query in the SQLite Manager in Firefox for the same database, it returns me the correct data. Please, help me find my mistakes, I'm really exhausted of this.
Here is the query I do in Manager:
SELECT loggerID, invertorID FROM records WHERE presetID=1 AND plantID IN ('3','2','1','6','5','4')
And here are logged values from the code:
preset: 1
plants: '3','2','1','6','5','4'
Thanks a lot!
I have recently been working on similar query.
I had a NSMutableArray which stored a list of ID's. I joined them as a string using the function componentsJoinedByString.
I then had a NSString object which held my SQL statement, using the stringWithFormat function.
So your code to generate the SQLite query could be along the lines of:
NSString * query = [NSString stringWithFormat:#"SELECT loggerID, invertorID FROM records WHERE presetID IN (%d) AND plantID IN (%#)",presetID,[plantsList componentsJoinedByString:#","]];
Hope this helps.

Problem while scrolling Table View

I have the following problem while i scroll the table view:
NSCFString objectAtIndex:]: unrecognized selector sent to instance
I create NSDictionary tableContents and when i scroll it becomes deallocated.
This is my code:
- (void)viewDidLoad {
lessonsInGroup1 = [NSMutableArray array];
lessonsInGroup2 = [NSMutableArray array];
lessonsInGroup1 = [self grabRowsInGroup:#"1"];
lessonsInGroup2 = [self grabRowsInGroup:#"2"];
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:lessonsInGroup1,#"General Information",lessonsInGroup2,#"LaTeX Examples", nil];
//[[tableContents alloc] init];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[lessonsInGroup1 release];
[lessonsInGroup2 release];
//[table reloadData];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
- (NSMutableArray *) grabRowsInGroup:(NSString*)GroupID{
NSMutableArray *groupOfLessons;
groupOfLessons = [[NSMutableArray alloc] init];
char *sqlStatement;
int returnCode;
sqlite3_stmt *statement;
NSString *databaseName;
NSString *databasePath;
// Setup some globals
databaseName = #"TexDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
fprintf(stderr, "Error in opening the database. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
sqlStatement = sqlite3_mprintf(
"SELECT * FROM Lessons WHERE LessonGroup = '%s';", [GroupID UTF8String]);
returnCode =
sqlite3_prepare_v2(database,
sqlStatement, strlen(sqlStatement),
&statement, NULL);
if(returnCode != SQLITE_OK) {
fprintf(stderr, "Error in preparation of query. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
returnCode = sqlite3_step(statement);
while(returnCode == SQLITE_ROW) {
NSString *aLessonID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *aLessonGroup = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSString *aLessonTopic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSString *aLessonText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
NSString *aLessonCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
NSString *aLessonPicture = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
/*NSLog(aLessonID);
NSLog(aLessonGroup);
NSLog(aLessonTopic);
NSLog(aLessonText);
NSLog(aLessonCode);
NSLog(aLessonPicture);*/
// Create a new busCit object with the data from the database
Lesson *lesson = [[Lesson alloc] initWithLessonID:aLessonID LessonGroup:aLessonGroup LessonTopic:aLessonTopic LessonText:aLessonText LessonCode:aLessonCode LessonPicture:aLessonPicture];
[groupOfLessons addObject:lesson];
returnCode = sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_free(sqlStatement);
return [groupOfLessons autorelease];
}
What does your #property for tableofContents look like?
Also, you are going to run into issues with
[lessonsInGroup1 release];
[lessonsInGroup2 release];
because you are autoreleasing those in the grabRowsInGroup:
So, you don't need to call release them.
Looks like you are calling objectAtIndex on NSString. It should rather be some array

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.

How to dynamically sorting an NSMutableArray in Objective-C?

I am retrieving rows from SQLite table, then dynamically creating an object, and then adding the object to an NSMutableArray. My problem is that I am unable to figure out a way to dynamically sort the objects in the array based on the distance attribute (which is a double), as I am adding each object to the NSMutableArray in a for-loop, from smallest to largest.
My relevant code looks like this:
sqlite3 *database;
//Init the restaurant array
restaurants = [[NSMutableArray alloc] init];
CLLocation *firstLocation = [[[CLLocation alloc] initWithLatitude:userLatitude longitude:userLongitude] autorelease];
//Open the database from the users filesystem
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
//setup the SQL statement and compile it for faster access
const char *sqlStatement = "select * from restaurant";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
//read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCity = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aProvinceState = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aPostalZipCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aCountry = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aPhoneNumber = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aHours = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
double aLat = sqlite3_column_double(compiledStatement, 9);
double aLon = sqlite3_column_double(compiledStatement, 10);
CLLocation *secondLocation = [[[CLLocation alloc] initWithLatitude:aLat longitude:aLon] autorelease];
CLLocationDistance restDistance = [secondLocation distanceFromLocation:firstLocation];
CLLocationDistance distanceKm = restDistance / 1000.0;
NSString *aDist = [[NSString alloc] initWithFormat: #"%f", distanceKm];
Restaurant *restaurant = [[Restaurant alloc] initWithName:aName address:aAddress city:aCity provinceState:aProvinceState postalZipCode:aPostalZipCode country:aCountry phoneNumber:aPhoneNumber hours:aHours latitude:aLat longitude:aLon distance:aDist];
//add the restaurant object to the restaurant array
[restaurants addObject:restaurant];
[restaurant release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
Once this function has finished its course, the restaurants array should be a sorted array containing restaurant objects that are in order of nearest (smallest distance double value) to furthest (largest distance double value).
Use NSMutableArray's sortUsingSelector to call a comparison function on your Restaurant object.
#implementation Restaurant
- (double) distance { return _distance; }
- (NSComparisonResult) compareDistance:(Restaurant *) iRHS {
double lhs, rhs;
lhs = [self distance];
rhs = [iRHS distance];
if ( lhs < rhs ) return NSOrderedAscending;
if ( lhs > rhs ) return NSOrderedDescending;
return NSOrderedSame;
}
#end
...
[restaurants sortUsingSelector: #selector(compareDistance:)];