Sqlite data not getting fetching - iphone

I am trying fetch the value from data base But it is not getting
I am trying this code but didn't get the value ,When i use the Break point on the program
I am having Longitude,Latitude his data type is double in data base
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from Location"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
NSLog(#"%i",i); **//over here i am getting the 101 value in console** And my pointer getting out from here
NSString *dLongitude = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *dLatitude = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
[locations addObject:[NSString stringWithFormat:#"%# ,%#",dLongitude,dLatitude]];
NSLog(#"%#",locations);
}
result = [locations componentsJoinedByString:#" "]; // same as `fake_location`
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
NSLog(#"%i",i); **//over here i am getting the 101 value in console** And my pointer getting out from here
double longitude = sqlite3_column_double(compiledStatement, 3);
double latitude = sqlite3_column_double(compiledStatement, 4);
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f",longitude,latitude] autorelease];
[locations addObject:coords];
NSLog(#"%#",locations);
}

Change the code to the following :
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from UserJourneyLocation"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int i = sqlite3_step(compiledStatement);
// NSLog(#"%i",i); / comment this line or use NSLog(#"%d",i);
// Make sure your longitude is double in database. else change the fetching value declaration
// We use 0 for dLongitude instead of 3 because in the select statement, it is the first value to be fetched irrespective of your table structure
// and same for dLatitude.
double dLongitude = sqlite3_column_double(compiledStatement, 0);
double dLatitude = sqlite3_column_double(compiledStatement, 1);
[locations addObject:[NSString stringWithFormat:#"%d ,%d",dLongitude,dLatitude]];
NSLog(#"%#",locations);
}
result = [locations componentsJoinedByString:#" "]; // same as `fake_location`
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

Related

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

Select query not working in SQLite

i am running a method for containing select query, but compiled statement is not working the break point skips the line where it declares it and when i puts the cursor on it it shows no value, Here's the code i am using:
-(NSMutableArray *)GetAllPartsName
{
NSString *path = [self getDBPath];
// Open the database from the users filessytem
NSMutableArray *Parts=[[[NSMutableArray alloc]init]autorelease ];
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
NSString *sqlQuery = [NSString stringWithFormat:#"SELECT Parts_Name FROM Parts"];
NSLog(#"%#",sqlQuery);
const char *sqlStatement = [sqlQuery UTF8String];
//The break point skips the sqlite3_stmt.
sqlite3_stmt *compiledStatement;
//when i put the cursor over compiledStatement it shows no value
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
NSMutableDictionary *PositionDict=[[NSMutableDictionary alloc]init];
//setting the parts into dictionary
[PositionDict setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,0)] forKey:#"Parts_Name"];
[Parts addObject:PositionDict];
NSLog(#"%#",PositionDict);
[PositionDict release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return Parts;
}
Try FMDattabase (https://github.com/ccgus/fmdb)
BASIC:
FMDatabase *_db = [[FMDatabase databaseWithPath:[[self class] databaseFilePath]] retain];
[_db open];
NSMutableArray *emails = [[NSMutableArray alloc] init];
NSString * query = [NSString stringWithFormat:#"SELECT `email` FROM `email`"];
FMResultSet * result = [_db executeQuery:query];
while ([result next])
{
[emails addObject:[result stringForColumn:#"email"]];
}
return [emails autorelease];

Sqlite database file is getting encrypted or is not a database

I have no idea what was the problem is in my program. When run this select code for fetching data from SQlite in my program, the first time it crashes with this error message:
kill error while killing target (killing anyway):
warning: error on line 2179 of "/SourceCache/gdb/gdb-1510/src/gdb/macosx/macosx-nat-inferior.c" in function "macosx_kill_inferior_safe": (os/kern) failure (0x5x)
quit
Here's my insert code:
-(id)init {
self = [super init];
sqlite3 *database;
NSMutableArray *locations;
NSString *result = nil;
NSString *dbPath = [self getWritableDBPath];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from myLocation"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
double longitude = sqlite3_column_double(compiledStatement, 0);
double latitude = sqlite3_column_double(compiledStatement, 1);
NSLog(#"%f , %f",longitude,latitude);
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
NSLog(#"this location :-%#",locations);
//[coords release];
}
result = [locations componentsJoinedByString:#","]; // same as `fake_location`
NSLog(#"this for resulte data :- %#",result);
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
pointsArray = [[result componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] retain];
pointsArrayIndex = 0;
oldLocationsIndex = 0;
[result release];
oldLocations = [[NSMutableArray alloc] init];
return self;
}
The second time I run my application, it shows me that on the console:
Save Error: file is encrypted or is not a database
What do these errors mean, and how do I solve that?
You need to fire insert query using following:
-(void)insertLocation:(double)latitude withLongitude:(double)longitude
{
sqlite3_stmt *insertStatement = nil;
const char *sql = "insert into UserJourneyLocation(Latitude, Longitude) Values(?,?)";
int returnValue = sqlite3_prepare_v2(database, sql, -1, &insertStatement, NULL);
if(returnValue == SQLITE_OK)
{
sqlite3_bind_double(insertStatement,1,latitude);
sqlite3_bind_double(insertStatement,2,longitude);
if(sqlite3_step(insertStatement)==SQLITE_DONE)
{
//Data;
}
}
sqlite3_finalize(insertStatement);
}
Yes I have.
Go to iphone application document folder
/users/(yourname)/library/application support/iphone simulator/user/application
And remove all Targets.After that Restart your application.

Accessing an object through SQLIte database

I am passing an object to the method in which I am executing a query. My method is:
-(BOOL)searchWordInDatabase:(NSString *)string
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalkLanguageElement.sqlite"];
//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
const char *sql="select ImageName from tblLanguageElement where Category= string";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}
}
return NO;
}
But I am not getting the value of the String in the query. How can I do it?
There is a mistake in your query. You can not substitute a string like that. Do it in the following way.
NSString *sqlStr = [NSString stringWithFormat:#"select ImageName from tblLanguageElement where Category = '%#'", string];
char *sql = (char *)[sqlStr UTF8String];
Make sure that your database exists at that path you retrieve. And you can bind string variables as follows while executing statements.
const char *sql = "select ImageName from tblLanguageElement where Category = ?";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}

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.