Sqlite database file is getting encrypted or is not a database - iphone

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.

Related

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

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

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

Sqlite data not getting fetching

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

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