My code snippet is leaking - iphone

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];
}

Related

How to print all data in given table?

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..

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.

not able to insert record in table in objective c

I made iPad application in which,
I want to insert record into database table, but I am unable to do the same.
here is my code snippet,
-(void) insertRecordIntoTableNamed: (NSString *) symbol{
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
NSLog(#"sql=%#",sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0, #"Error updating table.");
}
}
my NSLog shows:
sql=INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('PATNI',datetime())
this statement is correct, but i am unable to see VALUES PATNI and datetime() in my database table
here is rest of the code,
NSString *filePahs = Nil;
-(NSString *) filePath {
filePahs=[[NSBundle mainBundle] pathForResource:#"companymaster" ofType:#"sql"];
NSLog(#"path=%#",filePahs);
return filePahs;
}
result of above method is:
path=/Users/krunal/Library/Application Support/iPhone Simulator/5.0/Applications/9FF61238-2D1D-4CB7-8E24-9AC7CE9415BC/iStock kotak.app/companymaster.sql
-(void) openDB {
//---create database---
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK )
{
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
-(void) getAllRowsFromTableNamed: (NSString *) tableName {
//---retrieve rows---
NSString *qsql = #"SELECT * FROM recentquotes";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) ==
SQLITE_OK) {
NSLog(#"b4 while");
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
[field1Str release];
}
//---deletes the compiled statement from memory---
sqlite3_finalize(statement);
NSLog(#"recentqotarray=%#",recentqotarray);
}
}
edit
i wrote this, and when i checked my log i got like this, "in find data" , i didn't got my sql=...
- (void) finddata
{
NSString *databasePath;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"in finddata");
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM recentquotes"];
NSLog(#"sql=%#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Inside recent quote table");
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSLog(#"Column name=%s",field1);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
NSLog(#"array=%#",recentqotarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
Thanks In Advance
In your:
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
Instead of '%#' try using \"%#\" , and check if it inserts into your db.
EDIT:
I've been working on DB a lot lately, and i've been able to successfully insert data in my sqlite, i'll write down what i use check if it helps:
NSArray*dirPath;
NSString*docDir;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:#"example.sqlite"];
BOOL success;
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Already present");
}
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"example" ofType:#"sqlite"];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(#"Created successfully");
}
const char*dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &myDB)==SQLITE_OK)
{
NSString*insertSQL=[NSString stringWithFormat:#"insert into extable (name) values (\"%#\")",[nametextField.text]];
const char*insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(myDB, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"ADDED!");
}
sqlite3_close(myDB);
}

How to retrieve a particular column from a database in iphone

in my project im using a database.There are almost 365 questions in that.so i want to get a particulat question for a particular day.i used the code below to fetch a qusestion from database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '365'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
when i use the above code it is printing the correct question from database.Also when i give the statement like qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"]; it is not fetching the question.
But when i use the below code it is not fetching from the database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
while (sqlite3_step(statement) == (SQLITE_ROW))
{
NSLog(#" iolo");
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
//NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
NSLog(#"%# gg",Q_NO);
}
sqlite3_reset(statement);
}
sqlite3_finalize(statement);
}
Can anyone tell me where im going wrong.Thanks in advance.
-(void)print{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == (SQLITE_ROW))
{
char *field0 = (char *)sqlite3_column_text(statement, 0);
char *field1 = (char *)sqlite3_column_text(statement, 1);
NSString *Q_NO = nil;
if(field0!=NULL){
Q_NO = [[NSString alloc] initWithUTF8String:field0];
}
NSString *Q_NO1 = nil;
if(field1!=NULL){
Q_NO1 = [[NSString alloc] initWithUTF8String:field1];
}
NSLog(#"%# %#",Q_NO, Q_NO1);
[Q_NO release];
[Q_NO1 release];
}
}
sqlite3_finalize(statement);
}

Exception while reading an empty table

Iam trying to read data from a table.
Initially it is empty. If i tried to read at that time it will cause an exception.
My code is given Below
-(NSMutableArray *) selectDataFrom:(NSString *) tableName
{
NSString *qsql = [NSString stringWithFormat:#"SELECT * FROM '%#' ",tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( dataBase, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK)
{
NSLog(#"INSIDE IF");
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"INSIDE WHILE");
// my code
}
}
return allData;
}
The first NSLog("INDISE IF"); is printed.
But the second one is not printing.
Mention some books to learn sqlite3 statements of iPhone [ eg: sqlite_prepare_v2();] not SQL
[ Sorry for my poor English]
THIS IS THE FULL CODE
-(NSMutableArray *) selectDataFrom:(NSString *) tableName
{
allData = [[NSMutableArray alloc] init];
NSString *qsql = [NSString stringWithFormat:#"SELECT * FROM '%#' ",tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( dataBase, [qsql UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"REACHED 1");
myProgram = [[Programs alloc] init];
char *date = (char *) sqlite3_column_text(statement, 0);
myProgram.nss_Date = [[NSString alloc] initWithUTF8String:date];
char *type = (char *) sqlite3_column_text(statement, 3);
myProgram.nss_Type = [[NSString alloc]initWithUTF8String:type];
[nsma_allDonorsMA addObject:d_OneDonor];
}
}
else {
// NSLog(#"failed to select data");
}
return allData;
}
Try enabled breakpoints on exceptions and run your app in the debugger. It will show you exactly where you are calling objectAtIndex:. (It is not in the above code)
Where is your sqlite3_finalize() ??
You should release sqlite3_stmt structure in your sqlite3_prepare_v2 block, as following.
sqlite3_stmt *sql_stmt;
if (sqlite3_prepare_v2(...) == SQLITE_OK)
{
....
sqlite3_finalize(sql_stmt);
}