Problem With Sqlite Data Retrieving - iphone

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.

Related

How to get int data from iphone sqlite data base

I am getting data from iphone sqlite like this. I have 6 records in the table.
My table has fields responses_Id, participant_Id, answer_option, answer_text, update_date_time only all are varchar fields except responses_Id and participant_Id)
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.participant_Id=(This is integerin table)
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
When I NSlog data it does not show any things.
Look into the SQLite Documentation. All result values from queries are defined there.
You can use sqlite3_column_int for Integers similar to sqlite3_column_text for Text
NSNumber *primaryKey = [NSNumber numberWithInt:(int)sqlite3_column_int(selectstmt, 0)];
while(sqlite3_step(selectAllStmt) == SQLITE_ROW)
{
NSLog(#"record found");
char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if (temp!=nil) {
intId=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
// [pool release];
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey;
NSInteger intparticipant_Id;
char *temp = (char *)sqlite3_column_text(selectstmt, 0);
if (temp!=nil) {
primaryKey=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
temp = (char *)sqlite3_column_text(selectstmt, 1);
if (temp!=nil) {
intparticipant_Id=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
coffeeObj.participant_Id=intparticipant_Id;
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
Note:- char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if(temp != NULL)
str = [NSString stringWithUTF8String:temp];
else
str = #"";
temp =NULL;
If you want to take integer then you can do type casting "str = [NSString stringWithUTF8String:temp];" here......

how to check in iphone application if there is any data in sqlite data base

how to check at the start of the app wether there is data in sqlite or not if data is available in data base then it should upload other wise normally work the application
i will upload this data using post and using php for to upload data to server.
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select response_Id,question_id,answer_option,answer_text,update_date_time from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.question_Id = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
coffeeObj.answer_text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,3)];
coffeeObj.update_date_time = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
int count=[appDelegate.coffeeArray count];
NSLog(#"count is beofore getting values %d",count);
[appDelegate.coffeeArray addObject:coffeeObj];
int countone=[appDelegate.coffeeArray count];
NSLog(#"count is after getting values %d",countone);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
You can get number of rows present into the database by:
SELECT COUNT(*) FROM table;
if it returns 0 then your table is empty.
//update...................
const char *sqlQuery="Select count(*)from yourTable";
if(sqlite3_prepare_v2(database, sqlQuery, -1, &queryStatement, NULL)==SQLITE_OK)
{
while (sqlite3_step(queryStatement)==SQLITE_ROW)
{
const char *count=(const char *)sqlite3_column_text(queryStatement, 0);
NSString *rowCount=[NSString stringWithCString:count encoding:NSASCIIStringEncoding];
//here you will get the number of rows in string format;
}
}

SQLite and OBJ-C DB clear when launch application

I've a SQLite db on this position
/Users/software/Library/Application Support/iPhone Simulator/5.0/Applications/723EEE91-CB9D-4A27-8492-D61E127E72B7/myAPP.app/localDB.sqlite
No problems on write, delete or read data.
For example if I write on DB and close application, I find data in my DB, but if I restart the app my DB will clear. Can someone tell me why?
This is an example of a DB instance
SQLiteUtilities *db = [[SQLiteUtilities alloc]init:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"localDB.sqlite"]];
[db loadValuesFromQuery:#"SELECT * FROM categories;"];
for (int i = 0; i < [db getSize]; i++) {
NSLog(#"-- %#", [db objectAtIndex:i]);
}
[db release];
-(void)loadValuesFromQuery:(NSString *)query {
GenericRecord *record = [[[GenericRecord alloc]init] autorelease];
if (sqlite3_open([pathDB UTF8String], &database) == SQLITE_OK) {
// query che ricava i valori
const char *sql = (const char *) [query UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
// ricaviamo i valori letti dalla query
record.uniqueID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
record.superID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
record.subSuperID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
record.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
record.description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
record.price = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
record.note = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
record.pictureURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 8)];
record.catName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 9)];
record.subCatName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 10)];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 11) length:sqlite3_column_bytes(selectstmt, 11)];
if(data) record.imageBig = [UIImage imageWithData:data];
[self.list addObject:record];
}
}
}
sqlite3_close(database);
}
Also curious why I'm seeing so much raw sqlite3 work these days - any reason you're not using Core Data? Just a suggestion - it may not fit your needs (i.e., schema already exists and you're downloading it directly, etc).

iPhoneSdk, SQLite database search query not work

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.

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