iOS retrieve sqlite3 data and store it in NSObject array - ios

I might be doing this all wrong as I am still new to Objective C.
I am trying to retrieve data from an sqlite3 database and store it in a NSObject array.
Here is the viewDidLoad method in my implementation file.
- (void)viewDidLoad
{
[super viewDidLoad];
clients = [[NSMutableArray alloc] init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM clients"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW) {
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc]initWithUTF8String:field1];
char *field2 = (char *) sqlite3_column_text(statement, 1);
NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
char *field3 = (char *) sqlite3_column_text(statement, 2);
NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];
char *field4 = (char *) sqlite3_column_text(statement, 3);
NSString *field4Str = [[NSString alloc]initWithUTF8String:field4];
char *field5 = (char *) sqlite3_column_text(statement, 4);
NSString *field5Str = [[NSString alloc]initWithUTF8String:field5];
char *field6 = (char *) sqlite3_column_text(statement, 5);
NSString *field6Str = [[NSString alloc]initWithUTF8String:field6];
char *field7 = (char *) sqlite3_column_text(statement, 6);
NSString *field7Str = [[NSString alloc]initWithUTF8String:field7];
char *field8 = (char *) sqlite3_column_text(statement, 7);
NSString *field8Str = [[NSString alloc]initWithUTF8String:field8];
char *field9 = (char *) sqlite3_column_text(statement, 8);
NSString *field9Str = [[NSString alloc]initWithUTF8String:field9];
ClientObj *c1 = [[ClientObj alloc] initWithCompanyName:field1Str firstName:field2Str lastName:field3Str email:field4Str workPhone:field5Str mobilePhone:field6Str streetAddress:field7Str city:field8Str postalCode:field9Str];
}
}
self.clients = [NSArray arrayWithObjects:c1,c2,c3,c4, nil];
}
I am trying to increment *c1 each time the while statement loops through the database. eg. c1, c2 ,c3, c4
I am then trying to add each ClientObj created from the database loop above to the clients array but I am not sure how to do this.
Any help or advice is very much appreciated

Initialize the array once before the loop:
self.clients = [[NSMutableArray alloc] init];
and then just add each client object to the array inside the loop:
while (sqlite3_step(statement) == SQLITE_ROW) {
// ...
ClientObj *c = [[ClientObj alloc] initWithCompanyName:field1Str firstName:field2Str lastName:field3Str email:field4Str workPhone:field5Str mobilePhone:field6Str streetAddress:field7Str city:field8Str postalCode:field9Str];
[self.clients addObject:c];
}

Related

Call function in appDelegate

//find all data from database
- (void) findAllSupplement
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM SupplementInformationTable"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSMutableArray *allRows = [[NSMutableArray alloc] init] ;
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement,0);
NSString *field1Str1 = [[NSString alloc] initWithUTF8String: field1];
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field1Str2 = [[NSString alloc] initWithUTF8String: field2];
char *field3 = (char *) sqlite3_column_text(statement,2);
NSString *field1Str3 = [[NSString alloc] initWithUTF8String: field3];
char *field4 = (char *) sqlite3_column_text(statement,3);
NSString *field1Str4= [[NSString alloc] initWithUTF8String: field4];
char *field5 = (char *) sqlite3_column_text(statement,4);
NSString *field1Str5 = [[NSString alloc] initWithUTF8String: field5];
char *field6 = (char *) sqlite3_column_text(statement,5);
NSString *field1Str6 = [[NSString alloc] initWithUTF8String: field6];
char *field7 = (char *) sqlite3_column_text(statement,6);
NSString *field1Str7= [[NSString alloc] initWithUTF8String: field7];
char *field8 = (char *) sqlite3_column_text(statement,7);
NSString *field1Str8 = [[NSString alloc] initWithUTF8String: field8];
char *field9 = (char *) sqlite3_column_text(statement,8);
NSString *field1Str9 = [[NSString alloc] initWithUTF8String: field9];
NSMutableDictionary *dataDictionary=[[NSMutableDictionary alloc]init];
[dataDictionary setObject:field1Str1 forKey:#"supplementIdentity"];
[dataDictionary setObject:field1Str2 forKey:#"supplementName"];
[dataDictionary setObject:field1Str3 forKey:#"supplementDescription"];
[dataDictionary setObject:field1Str4 forKey:#"offerIdentity"];
[dataDictionary setObject:field1Str5 forKey:#"offerName"];
[dataDictionary setObject:field1Str6 forKey:#"offerDescription"];
[dataDictionary setObject:field1Str7 forKey:#"flavourIdentity"];
[dataDictionary setObject:field1Str8 forKey:#"imageLink"];
[dataDictionary setObject:field1Str9 forKey:#"quantityPurchase"];
// Add the string in the array.
[allRows addObject:dataDictionary];
NSLog(#"Match found") ;
//send all data to the cart container screen
CartContainer *objCartContainer=[[CartContainer alloc]init];
objCartContainer.arrayConatinLocalDataFromDB=allRows;
}
sqlite3_finalize(statement);
NSLog(#"%#",allRows);
}
sqlite3_close(_contactDB);
}
}
how i can call this function in app delegate ?this function is declared and define in view controller named productDetail.m .And i want to execute this function for my entire app. help will be appreciated.
Write the function in Appdelegate.m
And call from viewController.m
form this code:
AppDelegate *appDelegate;
appDelegate= (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate findAllSupplement];
Or you can declare the funtion globally. like:
In ViewController.h
+ (void) findAllSupplement;
And Define the funtion in ViewControler.m
+ (void) findAllSupplement
{
// your code here
}
And you can call the funtion from any class.

unknown error in sqlite in iOS?

I have made a function to get data from sqlite but somehow i am getting unknown error.I have used prepare statement concept here.Other functions like this are working fine but not this function.Please tell me what is the issue?
- (SubComponent*) getSeSubComponentDataBySubclientClientInspectionid:(NSString*)componentid : (NSString *)subclientid : (NSString *)clientId : (NSString *)inspectionid
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *query_stmt = "select * FROM sesubcomponent WHERE subcomponentid = ? AND subclientid = ? AND clientid = ? AND inspectionid = ?";
SubComponent *resultArray = [[SubComponent alloc]init];
if (sqlite3_prepare_v2(database,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
componentid=[NSString stringWithFormat:#"%#",componentid];
subclientid=[NSString stringWithFormat:#"%#",subclientid];
clientId=[NSString stringWithFormat:#"%#",clientId];
inspectionid=[NSString stringWithFormat:#"%#",inspectionid];
sqlite3_bind_text(statement, 1, [componentid UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [subclientid UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, [clientId UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, [inspectionid UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *component_id = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
resultArray.componentid = component_id;
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
resultArray.componentName = name;
NSString *createddate = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
resultArray.componentcreateddate = createddate;
NSString *subclientid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 3)];
resultArray.componentsubclientid = subclientid;
NSString *clientid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 4)];
resultArray.componentClientid = clientid;
NSString *entityid = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 5)];
resultArray.componentEntityid = entityid;
NSString *inspectionid = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 6)];
resultArray.componentinspectionid = inspectionid;
NSString *clientName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 8)];
resultArray.componentClientName = clientName;
NSString *subclientName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 9)];
resultArray.componentSubclientName = subclientName;
sqlite3_finalize(statement); sqlite3_close(database);
sqlite3_close(database);
return resultArray;
}
else
{
NSLog(#"%s getSeSubComponentDataBySubclientClientInspectionid arrow is ",sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
}
else
{
NSLog(#"getSeSubComponentDataBySubclientClientInspectionid error is %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return nil;
}

How to fetch data from table in Sqlite in ios?

I am working with the SQLite i am able to create the table and alter table but after adding columns to the table, data is not fetching.
Up to now my implementation inserting table values like below
NSString *sqlString=[NSString stringWithFormat:#"insert into %#(toid,fromid,msg,timedate,left,messageID,chatStatus) values('%#','%#','%#','%#',%d,'%#','%#')",tableName,userid,friendid,message,timedate,(int)leftright,messageID,chatStatus];
below i am fetching data from table
-(NSMutableArray *)AllRowFromTableName:(NSString *)tableName withUserID:(NSString *)userid withFriendID:(NSString *)friendid
{
NSMutableArray *array=[[NSMutableArray alloc] init];
NSString *sqlString=[NSString stringWithFormat:#"select *from chatTable where toid='%#' and fromid='%#'",userid,friendid];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sqlString UTF8String], -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
ChatHistorySkeleton *tempSkeleton=[[ChatHistorySkeleton alloc] init];
tempSkeleton.u_id =[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];//f_id
// NSString *strn = [NSString stringWithFormat:#"%#",tempSkeleton.mToID];
tempSkeleton.f_id=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
tempSkeleton.msg=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
//tempSkeleton.fromMe=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
// tempSkeleton.fromMe=((int)sqlite3_column_int(statement, 4)) ? YES : NO;
tempSkeleton.lft_rght=(int)sqlite3_column_int(statement, 4);
tempSkeleton.tim_dte=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
//if messageID Null
char *messageIDForEmptyCheck = (char *)sqlite3_column_text(statement, 6);
NSString *messageID1 = messageIDForEmptyCheck?[[NSString alloc]initWithUTF8String:messageIDForEmptyCheck]:#"";
tempSkeleton.messageID=messageID1;
//if chat status Null
char *chatStatus = (char *) sqlite3_column_text(statement,7);
NSString *chatStatus1 = chatStatus?[[NSString alloc]initWithUTF8String:chatStatus]:#"";
tempSkeleton.chatStatus=chatStatus1;
[array addObject:tempSkeleton];
// NSLog(#"IN LOOP=>%#",array);
}
}
return array;
}
I just alter table and added two columns messageID,chatstatus but these two values showing empty. What I am missing?

Loop through while(sqlite3_step(statement) until all the rows

I am storing multiple values in Sqlite database in my iOS app.
I need to retrieve the values under "cellForRowAtIndexPath"
- (NSString *) retrieveDetailText :(NSString *) emailAddress :(NSString *) uidText :(NSString *) folderName {
NSString *detailText = nil;
const char *dbpath = [databasePath UTF8String];
//SQLIte Statement
NSString *selettablequery = [NSString stringWithFormat:#"select * from MailFolderDBTable"];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
if (sqlite3_prepare(database, [selettablequery UTF8String], -1, &statement, NULL) ==SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *uidfield = (char *) sqlite3_column_text(statement, 5);
NSString *uidStr = [[NSString alloc] initWithUTF8String: uidfield];
NSLog(#"retrieveDetailText: uidStr: %#", uidStr);
if([uidStr isEqualToString:uidText]) {
char *emailstring = (char *) sqlite3_column_text(statement, 6);
NSString *detailTextData = [[NSString alloc] initWithUTF8String: emailstring];
NSData *data = [[NSData alloc] initWithBase64EncodedString:detailTextData options:NSDataBase64DecodingIgnoreUnknownCharacters];
detailText = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
From this code, I need to loop through at while(sqlite3_step(statement) == SQLITE_ROW)
As I am calling retrieveDetailText under cellForRowAtIndexPath, and it is not looping through here while(sqlite3_step(statement) == SQLITE_ROW), It checks if([uidStr isEqualToString:uidText]) only one time.
How can i loop through while(sqlite3_step(statement) until all the rows checked and get the value.
If you only need one row which satisfies uidText, then you can change your query no?
//SQLIte Statement
NSString *selettablequery = [NSString stringWithFormat:#"select * from MailFolderDBTable where uid = %#", uidText];
Otherwise, you can fetch all the data before loading your tableView, in an array and then use it as your tableView data source.

How to Show Distinct Value From Sqllite Table in iOS?

i am Newbie in iOS Development, and First time Use Sqllite database so Sorry For this Question but i am So Confusing Please Give me Solution for this.
I added Data in to My Sqllite Table Like as
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_myDatabase) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO ALLREADTABLE (PostId, PostTitle, ImageLink, ShortDescription,Category,PostDate) VALUES (\"%#\", \"%#\", \"%#\", \"%#\",\"%#\",\"%#\")",
post_id, cell.headLabel.text, image,self.shortDiscription,cell.categoryLabel.text,cell.timeLabel.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_myDatabase, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSString *string=[NSString stringWithFormat:#"Value Added %# %# %# %# %# %#",post_id, cell.headLabel.text, image,self.shortDiscription,cell.categoryLabel.text,cell.timeLabel.text];
NSLog(#"String %#",string);
} else
{
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(_myDatabase);
}
Then it is added data in to Data Base as I want and it also added Duplicate Value in to table , so For Distinct Value i Write a Code to Fetch data like as
- (void)getTextFomDB
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
#"sampleDatabase.db"]];
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_myDatabase) == SQLITE_OK)
{
NSString *querySQL = #"SELECT DISTINCT PostId, PostTitle, ImageLink, ShortDescription,Category,PostDate FROM ALLREADTABLE";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_myDatabase, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
[self.postId removeAllObjects];
[self.postTitle removeAllObjects];
[self.imageLink removeAllObjects];
[self.shortDecsription removeAllObjects];
[self.category removeAllObjects];
[self.postDate removeAllObjects];
while (sqlite3_step(statement) == SQLITE_ROW) {
//NSString *personID = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
NSString *postId = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)];
NSString *postTitle = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 2)];
NSString *ImageLink = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 3)];
NSString *shortDescrip = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 4)];
NSString *Category = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 5)];
NSString *postDate = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 6)];
[self.postId addObject:[NSString stringWithFormat:#"%# ", postId]];
[self.postTitle addObject:[NSString stringWithFormat:#"%# ",postTitle]];
[self.imageLink addObject:[NSString stringWithFormat:#"%#",ImageLink]];
[self.shortDecsription addObject:[NSString stringWithFormat:#" %#",shortDescrip]];
[self.category addObject:[NSString stringWithFormat:#" %#",Category]];
[self.postDate addObject:[NSString stringWithFormat:#" %#",postDate]];
}
sqlite3_finalize(statement);
}
sqlite3_close(_myDatabase);
}
}
Then it Give me Error like as
[NSPlaceholderString initWithUTF8String:]: NULL cString
Here I want Distinct Value From My SqlliteTable. please Give me Solution For that. I know It is easy But i am Newbie in Database so please Sorry
and Thanks in advance.
You are using initWithUTF8String to get values from database, So if there is a field in database which accept null data than it will gives you an error when you are trying to fetch null data from database.
I suggest you replace all data retrieving code like
NSString *postId = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)];
with below code:
NSString *postId = [NSString stringWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
This will replace not null data to an empty string.
This is being caused by trying to create a NSString object with a NULL string. It is on one of these lines:
[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, ...)];
So, before you create a NSString with the results of the sql statement you need to check for NULL like this:
char *tmp = sqlite3_column_text(statement, 1);
if (tmp == NULL)
postId = nil;
else
postId = [[NSString alloc] initWithUTF8String:tmp];
Reference: lnafziger

Resources