Working with SQLite in IOS - objective-c

Hello, I am using following code to implement SQLite Database in Application. Friends have you any other easiest way to implement
this, Which work with all the content of SQLite Database.
// .h File of DBManager
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface DBOperation : NSObject
{
}
+(void)OpenDatabase:(NSString*)path; //Open the Database
//+(void)finalizeStatements;//Closing and do the final statement at application exits
+(void)checkCreateDB;
//+(int) getLastInsertId;
+(BOOL) executeSQL:(NSString *)sqlTmp;
+(NSMutableArray*) selectData:(NSString *)sql;
#end
//
// DBOperation.m
// Puzzle
//
// Created by hbmac1 on 9/22/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "DBOperation.h"
static sqlite3 *database = nil;
static int conn;
#implementation DBOperation
+(void)checkCreateDB
{
#try {
NSString *dbPath,*databaseName;
databaseName=#"pointtable.sqlite";
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [docPaths objectAtIndex:0];
dbPath = [docDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fm = [NSFileManager defaultManager];
success=[fm fileExistsAtPath:dbPath];
if(success)
{
[self OpenDatabase:dbPath];
return;
}
NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
[self OpenDatabase:dbPath];
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
}
}
//Open database
+ (void) OpenDatabase:(NSString*)path
{
#try
{
conn = sqlite3_open([path UTF8String], &database);
if (conn == SQLITE_OK) {
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
#catch (NSException *e) {
NSLog(#"%#",e);
}
}
+(NSMutableArray*) selectData:(NSString *)sql
{
#try
{
if (conn == SQLITE_OK)
{
sqlite3_stmt *stmt = nil;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
[NSException raise:#"DatabaseException" format:#"Error while creating statement. '%s'", sqlite3_errmsg(database)];
}
NSMutableArray *obj = [[NSMutableArray alloc]init];
int numResultColumns = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
numResultColumns = sqlite3_column_count(stmt);
#autoreleasepool {
NSMutableDictionary *tmpObj = [[NSMutableDictionary alloc]init];
for(int i = 0; i < numResultColumns; i++){
if(sqlite3_column_type(stmt, i) == SQLITE_INTEGER){
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%i",sqlite3_column_int(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%f",sqlite3_column_double(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
if ( tmpStr == nil) {
tmpStr = #"";
}
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_BLOB) {
}
else if (sqlite3_column_type(stmt, i) == SQLITE_NULL) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = #"";
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
}
}
[obj addObject:tmpObj];
}
}
return obj;
} else {
return nil;
}
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return nil;
}
}
+(BOOL) executeSQL:(NSString *)sqlTmp {
#try {
if(conn == SQLITE_OK) {
const char *sqlStmt = [sqlTmp cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *cmp_sqlStmt1;
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt1, NULL);
returnValue == SQLITE_OK ? NSLog(#"\n Inserted \n") :NSLog(#"\n Not Inserted \n");
sqlite3_step(cmp_sqlStmt1);
sqlite3_finalize(cmp_sqlStmt1);
if (returnValue == SQLITE_OK)
{
return TRUE;
}
}
return FALSE;
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return NO;
}
}
#end

Check FMDB, it is very powerful and a lot easier to work with

(void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; NSFileManager *filemgr=[NSFileManager defaultManager]; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { char *errmsg; const char *sql_stmt="CREATE TABLE IF NOT EXISTS EVENT(EVENTID INTEGER PRIMARY KEY AUTOINCREMENT,ENAME TEXT,ETIME TEXT,TIMAGE TEXT)"; if(sqlite3_exec(eventDb,sql_stmt,NULL,NULL,&errmsg)!=SQLITE_OK) { NSLog(#"falied"); } sqlite3_close(eventDb); } else { NSLog(#"failed to open/create database"); }} //insert dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; sqlite3_stmt *statement; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { { { NSString *insertSQL=[NSString stringWithFormat:#" INSERT INTO EVENT(ENAME,ETIME,TIMAGE) VALUES (\"%#\",\"%#\",\"%#\")",_eventLbl.text,time,name]; const char *insert_stmt=[insertSQL UTF8String]; sqlite3_prepare_v2(eventDb,insert_stmt,-1,&statement,NULL); if(sqlite3_step(statement)==SQLITE_DONE) { NSLog(#"added"); } else { NSLog(#"fail to added"); } }}} //select NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; const char *dbpath=[databasePath UTF8String]; sqlite3_stmt *statment; if(sqlite3_open(dbpath,&eventDb)==SQLITE_OK) { NSString *querySQL=[NSString stringWithFormat:#"SELECT ENAME,ETIME,TIMAGE FROM EVENT "]; const char *query_stmt=[querySQL UTF8String]; if(sqlite3_prepare_v2(eventDb,query_stmt,-1,&statment,NULL)==SQLITE_OK) { while(sqlite3_step(statment)==SQLITE_ROW) { NSString ename=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 0)]; NSString eTIme=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 1)]; NSString IMAGENAME=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 2)]; event *g=[[event alloc] init]; g.eventname=ename; g.eventime=eTIme; g.eventImagename=IMAGENAME; [_arr addObject:g] } sqlite3_finalize(statment); } sqlite3_close(eventDb); } //tableview -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_tool count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *myId=#"myID"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:myId]; if (cell==nil) { [[NSBundle mainBundle]loadNibNamed:#"royalkitCell" owner:self options:nil]; cell=_toolCell; cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; } NSString *tname=[_tool objectAtIndex:indexPath.row]; _toolLabel=(UILabel *)[cell viewWithTag:10]; _toolLabel.text=tname; return cell; } Heading

Related

Does anyone know two NSString_s with the same hashes?

I want to test some cases in my app with strings which have the same hash, and I can't find it =(
I've found two strings with the same MD5. here But their hash are different. And googling didn't help me =(
NSString(MD5) category
Little story about NSDictionary
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSString *string1 = [self fileContentWithName:#"message1" encoding:NSUnicodeStringEncoding];
NSString *string2 = [self fileContentWithName:#"message2" encoding:NSUnicodeStringEncoding];
if (string1 != nil) {
if (string1.hash == string2.hash) {
NSLog(#"Hashes are the same");
} else {
if ([[string1 MD5Hash] isEqualToString:[string2 MD5Hash]]) {
NSLog(#"MD5 hases are equalfor:");
NSLog(#"lenght = %3ld - %#", string1.length, string1);
NSLog(#"lenght = %3ld - %#", string2.length, string2);
if ([string1 isEqualToString:string2]) {
NSLog(#"Strings are equal too");
} else {
NSLog(#"But strings are not equal");
}
}
}
}
}
#pragma mark -
- (NSString*)fileContentWithName:(NSString*)name encoding:(NSStringEncoding)enc
{
NSString *txtFilePath1 = [[NSBundle mainBundle] pathForResource:name ofType:#"bin"];
NSError *error = nil;
NSString *txtFileContents1 = [NSString stringWithContentsOfFile:txtFilePath1 encoding:enc error:&error];
return txtFileContents1;
}

Database is locked sqlite ios

I write a application have use sqlite save data. I add data to table success. But i can't delete content in table. It notify DATABASE IS LOCKED.
My code:
Code Delete in sqlite
//Xoá tài khoản
-(BOOL) delete_Account
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *delete_Statement = "DELETE FROM info";
if(sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL)==SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DELETE Account : %#", #"Ban da xoa thanh cong!");
return YES;
}
else{
NSLog(#"DELETE Account: %# %s",#"Xoa that bai",sqlite3_errmsg(database));
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
Full code
#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB{
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: #"Sync.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS info (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PASS TEXT, TOKEN TEXT, COMPANY TEXT, CUSTOMER TEXT)";
const char*sql_create_contact_db = "CREATE TABLE IF NOT EXISTS contact (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST TEXT, LAST TEXT, PHONE TEXT, EMAIL TEXT)";
if (sqlite3_exec(database, sql_statement, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table INFO");
}
if (sqlite3_exec(database, sql_create_contact_db, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table CONTACT");
}
sqlite3_finalize(statement);
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}
return isSuccess;
}
-(BOOL) add_Data_Info:(NSString *)username :(NSString *)password :(NSString *)token
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO info (name, pass, token, company, customer) VALUES (\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")", username, password, token, #"ON", #"OFF"];
const char *insert_Statement = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Thêm data vào database
-(BOOL) add_Data_Sync:(NSString *)first :(NSString *)last :(NSString *)phone : (NSString*)email
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO contact (first,last,phone,email) VALUES (\"%#\",\"%#\",\"%#\",\"%#\")", first, last, phone, email];
const char *insert_Statement = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Cập nhật token
-(BOOL) update_Data_Info:(NSString *)username : (NSString *) token
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE info Set token = \"%#\"where name = \"\"%#\")", token, username];
const char *update_Statement = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Cập nhật token
-(BOOL) update_Sw_Info:(NSString *)username : (NSString *) status
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE info Set company = \"%#\" where name = \"%#\" ", status, username];
const char *update_Statement = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Xoá tài khoản
-(BOOL) delete_Account
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *delete_Statement = "DELETE FROM info";
if(sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL)==SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DELETE Account : %#", #"Ban da xoa thanh cong!");
return YES;
}
else{
NSLog(#"DELETE Account: %# %s",#"Xoa that bai",sqlite3_errmsg(database));
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
-(BOOL)delete_All_Contact
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *deleteSQL = [NSString stringWithFormat:#"DELETE FROM contact"];
const char *delete_Statement = [deleteSQL UTF8String];
sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ROW)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
- (NSArray*) getInfo
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT name, token, pass, company, customer FROM info"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:name];
NSString *token = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
[resultArray addObject:token];
NSString *pass = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
[resultArray addObject:pass];
NSString *company = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 3)];
[resultArray addObject:company];
NSString *customer = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 4)];
[resultArray addObject:customer];
return resultArray;
}
else{
NSLog(#"Not found");
return nil;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return nil;
}
//Kiểm tra dữ liệu trong database
-(int)checkContact : (NSString *) txtPhone
{
int check = 0;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT COUNT(*) FROM contact WHERE phone = \"%#\"",txtPhone];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
check = 1;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return check;
}
#end

NSMutableArray writeToURL:url atomically:YES

I'm trying to create a file with an NSMutableArray with just NSStrings stringWithFormat objects inside, this is what i got:
- (IBAction)CreateMod:(id)sender {
NSLog(#"Finished Button Pressed");
NSString* CustomScript = [NSString stringWithFormat:#"//Made with UltimateMM \n %#",self.CS ];
NSArray* fileTypes = [[NSArray alloc] initWithObjects:#"js", nil];
NSSavePanel *spanel = [NSSavePanel savePanel];
[spanel setCanCreateDirectories:YES];
[spanel setCanSelectHiddenExtension:YES];
[spanel setAllowedFileTypes:fileTypes];
[spanel setTreatsFilePackagesAsDirectories:YES];
[spanel beginSheetModalForWindow:self.SecondaryWindow completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton)
{
NSURL *saveURL = [spanel URL];
NSLog(#"%#", saveURL);
NSError* error = nil;
if(_CST == true) {
NSLog(#"CustomScriptMade");
/*
BOOL didWrite = [CustomScript writeToURL:saveURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (didWrite == NO)
{
NSLog(#"CustomScript Write Error");
}
*/
}
if(_TTT == true) {
NSLog(#"TopicMade");
BOOL didWrite = [_TopicPR writeToURL:saveURL atomically:YES];
if (didWrite == NO)
{
NSLog(#"Topic Write Error");
}
}
_CST = false;
_TTT = false;
}
}];
}
I have the CustomScript writeToURL out so i can see if it crates the TopicPR, but it doesn't even open the NSSavePanel, Please Help.
thanks in advance!..

Sqlite3 step == SQLITE_ROW not working for me

As i am new to Xcode so no idea to fix this issue. Please help me out to figure the actual issue.
Database connection is build up, the query is execute, but I always get the message as : Result not found, after execution the query. :(
- (void)viewDidLoad
{
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;
const char *Database = [MyDBPath UTF8String];
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Status.text = #"Build Connection Successfully...!";
}
else
{
Status.text = #"Failed to open database...!";
}
[super viewDidLoad];
}
- (void) Find
{
const char *Database = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], 0, &SQLStatement, nil) == SQLITE_OK)
{
while (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
}
if (TextResult.text.length > 0)
{
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
//NSString *decode = [[NSString alloc]initWithCString:Query_Stmt encoding:NSUTF8StringEncoding];
//Status.text = decode;
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
Sqlite3_step(SQLStatement) == SQLITE_ROW __ nor working
Yes i resolved the issue…!!!!
actually i just change the path of the directory to direct to my DB path.
here is my final and working code… anyway thanks #HotLicks,,, #CL. :) :)
This works like a charm … :)
- (void) Find
{
MyDBPath = #"/Users/zaibi/Documents/IOSProjects/mydb.db";
MyDatabase = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
//NSString *decode = [[NSString alloc]initWithCString:Database encoding:NSUTF8StringEncoding];
//NSLog(#"%#",decode);
if (sqlite3_open(MyDatabase, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], -1, &SQLStatement, nil) == SQLITE_OK)
{
if (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
while this way of accessing the DB is just confusing… :/
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;
Sometimes it helps to read the documentation:
If the nByte argument is less than zero, then zSql is read up to the
first zero terminator. If nByte is non-negative, then it is the
maximum number of bytes read from zSql.

Code is bypassing Array creation Loop from a sqlite database

my NSMutableArray creation code is being bypassed altogether for some reason. in theory it is supposed to create an NSMutableArray based on an sqlite database. There is only one warning message and no errors. what am I missing?
the implementation file is:
#import "iProspectFresno LiteAppDelegate.h"
#import "MainViewController.h"
#import "Mine.h"
#import <Foundation/Foundation.h>
#implementation iProspectFresno_LiteAppDelegate
#synthesize window;
#synthesize mainViewController;
#synthesize mines;
-(void) checkAndCreateDatabase {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void) readMinesFromDatabase
{
sqlite3 *database;
mines = [[NSMutableArray alloc] init];
NSLog(#"readMinesFromDatabase initialized");
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select * from MinesoftheMotherLode";
sqlite3_stmt *compiledStatement;
NSLog(#"first if statement");
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSLog(#" second if statement initialized");
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSNumber *aentryNumber = [NSNumber numberWithInt:(int)sqlite3_column_int(compiledStatement, 1)];
NSString *amineName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 2)];
NSString *amineType = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 3)];
NSString *astatus = [NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 4)];
NSNumber *alatitude = [NSNumber numberWithDouble:(double)sqlite3_column_double(compiledStatement, 5)];
NSNumber *alongitude = [NSNumber numberWithDouble:(double)sqlite3_column_double(compiledStatement, 6)];
NSString *ametal =[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement, 7)];
BOOL *adisplay = NO;
NSNumber *acoverRegion =[NSNumber numberWithInt:(int)sqlite3_column_int(compiledStatement, 9)];
NSLog(#"mine", aentryNumber, amineName, amineType, astatus, alatitude, alongitude, ametal, adisplay, acoverRegion);
Mine *mine = [[Mine alloc] initWithEntryNumber:aentryNumber mineName:amineName mineType:amineType status:astatus latitudeInitial:alatitude longitudeInitial:alongitude metal:ametal display:adisplay coverRegion:acoverRegion];
[mines addobject:mine];
[mine release];
}
}
NSLog(#"created database successfully");
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
databaseName = #"MinesoftheMotherLode.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[self readMinesFromDatabase];
MainViewController *aController = [[MainViewController alloc] initWithNibName:#"MainView" bundle:nil];
self.mainViewController = aController;
[aController release];
mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
[window addSubview:[mainViewController view]];
[window makeKeyAndVisible];
}
The implementation file for Mines is here:
#import "Mine.h"
#implementation Mine
#synthesize entryNumber, mineName, mineType, status, latitudeInitial, longitudeInitial, metal, display, coverRegion;
-(id)initWithEntryNumber:(NSNumber *)e mineName:(NSString *)n mineType:(NSString *)t status:(NSString *)s latitudeInitial:(NSNumber *)l longitudeInitial:(NSNumber *)o metal:(NSString *)m display:(BOOL *)d coverRegion:(NSNumber *)c
{
self.entryNumber = e;
self.mineName = n;
self.mineType = t;
self.status = s;
self.latitudeInitial = l;
self.longitudeInitial = o;
self.metal = m;
self.display = d;
self.coverRegion = c;
return self;
}
#end
The NSLog "Second if statement initialized" is not showing up on the console. any ideas as to what needs to be fixed here? and yes I know, I should be using core data.
It seems you've answered your initial question about it loading. For your secondary question regarding the crash about the null string, you should be loading strings like this:
if (sqlite3_column_text(init_statement, 0) != NULL) {
self.someString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(init_statement, 0)];
} else {
self.someString = #"";
}