How to print all data in given table? - iphone

i am iPhone application developer, and now we understood the concept of database.
i want to print all data from database. but i m not getting how can i print all data. here is i pest some code. please give me correct direction to print all data..
for example in sql we print all data as "select * from contact5;" we fire this string. can we done in iPhone coding?
-(IBAction)PrintData:(id)sender
{
NSLog(#"Button Pressed");
sqlite3_stmt *statement1;
NSString *querySQL=#"SELECT * FROM CONTACT5";
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement1, NULL);
while (sqlite3_step(statement1) == SQLITE_ROW)
{
NSLog(#"Enter in the denger zone");
NSString *idField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 0)];
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 2)];
NSString *NameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 1)];
NSString *phoneFiels = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement1, 3)];
NSLog(#"ID is=%#",idField);
NSLog(#"Name is=%#",NameField);
NSLog(#"Address is=%#",addressField);
NSLog(#"Phone No. is=%#",phoneFiels);
[idField release];
[NameField release];
[phoneFiels release];
[addressField release];
}
sqlite3_finalize(statement1);
sqlite3_close(contactDB);
}
thanks in advance.

We are sharing Some come which is using NSMutableDictionary to store your data and you can easily use that code to print your data,where do you want
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "Select * from CalculateTime";
sqlite3_stmt *insertStmt;
if(sqlite3_prepare_v2(database, sql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0,#"Error: Failed to prepare statement with message '%s'.",sqlite3_errmsg(database));
arrayCountry = nil;
arrayCountry = [[NSMutableArray alloc]init];
arrayCity = nil;
arrayCity = [[NSMutableArray alloc]init];
arrayFlag = nil;
arrayFlag = [[NSMutableArray alloc]init];
arrayZone = nil;
arrayZone = [[NSMutableArray alloc]init];
NSString *str2;
while(sqlite3_step(insertStmt)==SQLITE_ROW)
{
char *row;
row = (char*)sqlite3_column_text(insertStmt, 0);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayCountry addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 1);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayCity addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 2);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayFlag addObject:str2];
}
row = (char*)sqlite3_column_text(insertStmt, 3);
if(row != NULL)
{
str2 = [NSString stringWithUTF8String:row];
[arrayZone addObject:str2];
}
}
}
Access these dictionary data to print anywhere..

Related

Inserting and reading image data in sqlite3 iphone

I have an app, that stores some info about account, including the image. Everything is great: tables are created, data can be saved, but the image is not (I can't understand if the image is not saving or it can't be retrieved from db). My code:
database table:
static const char *accountsTable = "CREATE TABLE IF NOT EXISTS tbl_accounts (unique_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, provider_id INTEGER, login TEXT, password TEXT, threshold INTEGER, is_need_push INTEGER, comment TEXT, image BLOB)";
my insert method:
-(BOOL) createAccountWithAccountData:(AccountsData *) accountData
{
NSInteger pushNotifications = accountData.isNeedPushNotifications ? 1 : 0;
const char *dbPath = [dataBasePath UTF8String];
if (sqlite3_open(dbPath, &database) == SQLITE_OK) {
NSString *insertSqlStatement = [NSString stringWithFormat: #"INSERT INTO tbl_accounts (provider_id, login, password, threshold, is_need_push, comment, image) values ('%d', '%#', '%#', '%d', '%d', '%#', '?')", accountData.providerId, accountData.logIn, accountData.password, accountData.threshold, pushNotifications, accountData.comment];
const char *insertStmt = [insertSqlStatement UTF8String];
if (sqlite3_prepare_v2(database, insertStmt, -1, &sqlStatement, NULL) == SQLITE_OK ) {
if (accountData.image != nil) {
NSLog(#"Image not null");
NSData *imageData = UIImageJPEGRepresentation(accountData.image, 1.0);
sqlite3_bind_blob(sqlStatement, 7, [imageData bytes], [imageData length], nil);
} else {
NSLog(#"image is nil");
}
if (sqlite3_step(sqlStatement) == SQLITE_DONE)
{
NSLog(#"Successfully created account data");
sqlite3_reset(sqlStatement);
sqlite3_close(database);
return YES;
} else {
NSLog(#"Unable to create account data");
sqlite3_reset(sqlStatement);
sqlite3_close(database);
return NO;
}
}
}
return NO;
}
and my get all accounts method:
-(NSArray *) getAllAccounts
{
const char *dbPath = [dataBasePath UTF8String];
NSMutableArray *allAccounts = [[NSMutableArray alloc] init];
if (sqlite3_open(dbPath, &database) == SQLITE_OK) {
NSLog(#"DB Opened");
NSString *findSqlStatement = [NSString stringWithFormat: #"SELECT * FROM tbl_accounts"];
const char *findStmt = [findSqlStatement UTF8String];
if (sqlite3_prepare_v2(database, findStmt, -1, &sqlStatement, NULL) == SQLITE_OK)
{
NSLog(#"statement was prepared");
while (sqlite3_step(sqlStatement) == SQLITE_ROW)
{
NSLog(#"Into the while loop");
NSInteger uniqueId = [[NSString stringWithUTF8String:(const char *) sqlite3_column_text(sqlStatement, 0)] integerValue];
NSInteger providerId = [[NSString stringWithUTF8String:(const char *) sqlite3_column_text(sqlStatement, 1)] integerValue];
NSString *logIn = [NSString stringWithUTF8String:
(const char *) sqlite3_column_text(sqlStatement, 2)];
NSString *password = [NSString stringWithUTF8String:
(const char *) sqlite3_column_text(sqlStatement, 3)];
NSInteger threshold = [[NSString stringWithUTF8String:(const char *) sqlite3_column_text(sqlStatement, 4)] integerValue];
NSInteger pushNotif = [[NSString stringWithUTF8String:(const char *) sqlite3_column_text(sqlStatement, 5)] integerValue];
NSString *comment = [NSString stringWithUTF8String:
(const char *) sqlite3_column_text(sqlStatement, 6)];
BOOL isNeedNotif = [self convertNSInteger:pushNotif];
int length = sqlite3_column_bytes(sqlStatement, 7);
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(sqlStatement, 7) length:length];
NSLog(#"itemLogin: %#", logIn);
NSLog(#"password : %#", password);
NSLog(#"data is: %#", data);
NSLog(#"comment is: %#", comment);
NSLog(#"isNeedNotif: %hhd", isNeedNotif);
UIImage *imageFromDb = nil;
if (data != nil)
imageFromDb = [[UIImage alloc] initWithData:data];
else
NSLog(#"No image");
if (imageFromDb) {
NSLog(#"Image");
} else {
NSLog(#"NoImage");
}
AccountsData *item = [[AccountsData alloc] initWithProviderId:providerId logIn:logIn password:password threshold:threshold isNeedPushNotifications:isNeedNotif comment:comment image:imageFromDb];
item.unique_id = uniqueId;
[allAccounts addObject:item];
NSLog(#"Item added to array");
NSLog(#"Array count: %d", [allAccounts count]);
}
}
sqlite3_reset(sqlStatement);
sqlite3_close(database);
}
return allAccounts;
}
I've tested it on the emulator and the Image data is (NSDATA, according to NSLog):
data is: <3f>
Please, help me!!!
INSERT INTO tbl_accounts (..., image) values (..., '?')
You are inserting a string that consists of the single character ?.
Parameter markers must not be quoted:
INSERT INTO tbl_accounts (..., image) values (..., ?)
Furthermore, the second parameter of sqlite3_bind_blob is the parameter number, and the statement has only one parameter; it must be 1, not 7.
Additionally, sqlite3_reset is necessary only if you want to reuse the statement (but harmless otherwise).
What you must never forget is to call sqlite3_finalize when you're done with the statement, and before you close the database.
In this code, just replace sqlite3_reset with sqlite3_finalize.

My code snippet is leaking

The below code snippet leaks when i am trying the build and analyse thing.
What is the problem in this code , pls let me know
- ( NSString *) getSubCategoryTitle:(NSString*)dbPath:(NSString*)ID{
NSString *subCategoryTitle;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select sub_category_name from sub_categories where id = %#",ID];
NSLog(#"%# I am creashes here", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
subCategoryTitle = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 0)];
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return [subCategoryTitle autorelease];
}
You allocate instance into subCategoryTitle in a loop, but don't release the previous allocation.
subCategoryTitle = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 0)];
Either (auto)release it, or directly go to the last row, and avoid this while, as it doesn't make much sense.
Example for creating only last object:
char * col_text = NULL;
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
col_text = sqlite3_column_text(selectstmt, 0);
}
if (col_text != NULL)
{
subCategoryTitle = [[NSString alloc] initWithUTF8String:col_text];
}

i want to store single string values in array but its save only last value and remove all first values

-(void) getAllRowsFromTableNamed:(NSString *) tableName
{
AppDelegate *app =[[UIApplication sharedApplication]delegate];
strNam = app.strName;
NSString *qsql = [ NSString stringWithFormat:#"SELECT * FROM %#", tableName];
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(db2, [qsql 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];
NSString *str =[[NSString alloc] initWithFormat:#"%# - %#- %#- %#", field1Str, field2Str, field3Str, field4Str];
NSLog(#"%#",str);
NSLog(#"%#",field1Str);
self.strDat = field1Str;
NSLog(#"%#", strDat);
array2 =[[NSMutableArray alloc]init];
[self.array2 addObject:self.strDat];
}
sqlite3_finalize(statement);
NSLog(#"%#",[array2 description]);
}
}
put your array's alloc out of the "while",
or you create the array2 every time you insert it
if( sqlite3_prepare_v2(db2, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK)
{
//here
array2 =[[NSMutableArray alloc]init];
while (sqlite3_step(statement) == SQLITE_ROW)
{
....
....
....
[array2 addObject:self.strDat];
}
}
initialize array before loop like this
-(void) getAllRowsFromTableNamed:(NSString *) tableName
{
AppDelegate *app =[[UIApplication sharedApplication]delegate];
strNam = app.strName;
NSString *qsql = [ NSString stringWithFormat:#"SELECT * FROM %#", tableName];
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(db2, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK)
{
array2 =[[NSMutableArray alloc]init];
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];
NSString *str =[[NSString alloc] initWithFormat:#"%# - %#- %#- %#", field1Str, field2Str, field3Str, field4Str];
NSLog(#"%#",str);
NSLog(#"%#",field1Str);
self.strDat = field1Str;
NSLog(#"%#", strDat);
[self.array2 addObject:self.strDat];
}
sqlite3_finalize(statement);
NSLog(#"%#",[array2 description]);
}
}

Reading SIM contacts in jailbroken iPhone

I am working on an application which needs to read the contacts from the SIM.
I know that it is not possible using the official Apple SDK.
I am developing this app for the jailbroken iPhones.
I have searched a lot but the only answer I got is NOT POSSIBLE.
Any help towards the path will really be appreciated.
NSString *addressbookDatabasePath = #"/private/var/wireless/Library/AddressBook/addressbook.db";
addressbookFileExist = [fileManager fileExistsAtPath:addressbookDatabasePath];
[fileManager release];
NSMutableArray *addressbook = [[NSMutableArray alloc] init];
if(addressbookFileExist) {
if ([fileManager isReadableFileAtPath:addressbookDatabasePath]) {
sqlite3 *database;
if(sqlite3_open([addressbookDatabasePath UTF8String], &database) == SQLITE_OK) {
sqlite3_stmt *compiledStatement;
NSString *sqlStatement = [NSString stringWithString:#"SELECT * FROM call;"];
int errorCode = sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1,
&compiledStatement, NULL);
if( errorCode == SQLITE_OK) {
int count = 1;
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSMutableDictionary *addressbookItem = [[NSMutableDictionary alloc] init];
int numberOfColumns = sqlite3_column_count(compiledStatement);
NSString *data;
NSString *columnName;
for (int i = 0; i < numberOfColumns; i++) {
columnName = [[NSString alloc] initWithUTF8String:
(char *)sqlite3_column_name(compiledStatement, i)];
data = [[NSString alloc] initWithUTF8String:
(char *)sqlite3_column_text(compiledStatement, i)];
[addressbookItem setObject:data forKey:columnName];
[columnName release];
[data release];
}
[callHistory addObject:callHistoryItem];
[callHistoryItem release];
count++;
}
}
else {
NSLog(#"Failed to retrieve table");
NSLog(#"Error Code: %d", errorCode);
}
sqlite3_finalize(compiledStatement);
}
}
}

How to list the resultset based on order using query

//===================================================================================
- ( NSMutableDictionary * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableDictionary *aTierTwoTemplateData = [[NSMutableDictionary alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData setObject:aId forKey:aValue];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return aTierTwoTemplateData;
}
I am able to get the resultset when i assign this to array , but it loses the order in which , i have stored in the dictionery.
Actually , i have stored the result set based on the position field .
When i assign the resultset into array , the order gets changed.
Please let me know how can i handle this situation.
This is not a duplicate, as i have a coulmn in the db as "position"
If you want to store data as key-value pair and maintain the order, then you can use combination of NSArray and NSDictionary.The same code will be:
//===================================================================================
- ( NSArray * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableArray *aTierTwoTemplateData = [[NSMutableArray alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData addObject:[NSDictionary dictionaryWithObject:aId forKey:aValue]];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return [aTierTwoTemplateData autorelease];
}
In this way you'll be having an array of dictionaries, where your values will be stored in the dictionary and the order of the data also will be preserved.