It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I create one application that use sqlite DB in it.
I have one problem and it is any time run my application add NSDictionary in my table sqlite. I want once check sqlite and if data exist in table sqlite not add else add it.
this my code:
ViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface ViewController : UIViewController
{
sqlite3 * database;
}
#end
ViewController.m
#import "ViewController.h"
#define DatabaseName #"data.sqlite"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *idd = [NSArray arrayWithObjects:#"122",#"234",#"453", nil];
NSArray *name = [NSArray arrayWithObjects:#"janatan",#"fred",#"john", nil];
NSArray *age = [NSArray arrayWithObjects:#"23",#"35",#"12", nil];
NSArray *sex = [NSArray arrayWithObjects:#"male",#"male",#"male", nil];
for (int i = 0; i < [idd count]; i++)
{
NSString * a = [idd objectAtIndex:i];
NSString * b = [name objectAtIndex:i];
NSString * c = [age objectAtIndex:i];
NSString * d = [sex objectAtIndex:i];
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:a,#"id",b,#"name",c,#"age",d,#"sex", nil];
NSString *query = [NSString stringWithFormat:#"insert into table1 (id,name,age,sex) values('%#','%#','%#','%#')",[dic objectForKey:#"id"],[dic objectForKey:#"name"],[dic objectForKey:#"age"],[dic objectForKey:#"sex"]];
NSLog(#"%#",query);
[self executeQuery:query];
}
}
-(NSString *) dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"PATH %#",[documentsDirectory stringByAppendingPathComponent:DatabaseName]);
return [documentsDirectory stringByAppendingPathComponent:DatabaseName];
}
/*==================================================================
METHOD FOR INSERTING DATA IN DATABASE
==================================================================*/
-(void)executeQuery:(NSString *)query
{
//NSLog(#"QUERY : %#",query);
sqlite3_stmt *statement;
if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
{
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) != SQLITE_DONE)
{
sqlite3_finalize(statement);
}
}
else
{
NSLog(#"query Statement Not Compiled");
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
else
{
NSLog(#"Data not Opened");
}
}
#end
also I want when NSDictionary changed for example arrays is Dictionary increase value update sqlite complete.
please explain me .
Use this method :
/*==================================================================
METHOD FOR CHECKING WHETHER RECORD EXISTS OR NOT IN DATABASE
==================================================================*/
-(BOOL)recordExistOrNot:(NSString *)query{
BOOL recordExist=NO;
if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK)
{
if (sqlite3_step(statement)==SQLITE_ROW)
{
recordExist=YES;
}
else
{
//////NSLog(#"%s,",sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
return recordExist;
}
It will return YES if record exists else not.
Ex :
NSString *query = [NSString stringWithFormat:#"select * from yourtable where column_name = 'column_name'"];
NSLog(#"query : %#",query);
BOOL recordExist = [self recordExistOrNot:query];
if (!recordExist) {
// Insert your data
}
Hope it helps you.
Related
I'm following some tutorials from youtube for sqlite crud operations. I have textfields with name, contact and address , when i hit save button it show message in console that data is saved but when i look at database it nothing appears there. My database path is correct and no errors in code but 'm confused why it isn't going. My path code is this,
-(void)copyandpaste{
NSArray *arr1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *str1 = [arr1 objectAtIndex:0];
strpath = [str1 stringByAppendingPathComponent:#"personinfo.sqlite"];
if (![[NSFileManager defaultManager]fileExistsAtPath:strpath]) {
NSString *local = [[NSBundle mainBundle]pathForResource:#"personinfo" ofType:#"sqlite"];
[[NSFileManager defaultManager]copyItemAtPath:local toPath:strpath error:nil];
}
NSLog(#"%#",strpath);
}
this method is called in appdelegate.m file,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self copyandpaste];
return YES;
}
I have mad NSObject class for database connection. the connection code is this,
-(id)init{
appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate]; //get all methods in AppDelegate
strmain = appdel.strpath;
return self;
}
-(NSMutableArray *)getalluser:(NSString *)query{
arrdata = [[NSMutableArray alloc]init];
if (sqlite3_open([strmain UTF8String], &(database))==SQLITE_OK) {
sqlite3_stmt *connection;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK) {
while (sqlite3_step(connection)==SQLITE_ROW) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
NSString *str12 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 0)]; //name in first column
NSLog(#"Checking");
NSString *str13 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 1)]; //contact in second column
NSString *str14 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 2)]; //address in third column
[dic setObject:str12 forKey:#"name"];
[dic setObject:str13 forKey:#"contact"];
[dic setObject:str14 forKey:#"address"];
[arrdata addObject:dic];
}
}
sqlite3_finalize(connection);
}
sqlite3_close(database);
return arrdata;
}
My save button code with query is this,
- (IBAction)btnSave:(id)sender {
NSString *saveDATA=[[NSString alloc]initWithFormat:#"insert into stuInfo values('%#','%#','%#')",txtName,txtContact,txtAddress];
dboperations *db = [[dboperations alloc ]init];
BOOL ds = [db getalluser:saveDATA];
if (ds) {
NSLog(#"Data Saved in database");
}else{
NSLog(#"Data is not Saved in database");
}
}
- (NSString*) saveData:(NSString *)name cont:(NSString *)contacts add:(NSString *)address
{
const char *dbpath = [YOUR_DATA_BASE_PATH UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#"=============saveData open==============");
const char * query="insert into YOUR_TABLE_NAME(name,contacts,address) values(?,?,?);";
sqlite3_stmt *inset_statement;
char *errMsg;
if (sqlite3_open(dbpath, &database)!=SQLITE_OK) {
NSLog(#"Error to Open");
return nil;
}
if (sqlite3_prepare_v2(database, query , -1,&inset_statement, NULL) != SQLITE_OK )
{
NSLog(#"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
NSLog(#"Error to Prepare");
return nil;
}
//No of data to insert
sqlite3_bind_text(inset_statement,1,[name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,2,[contacts UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,3,[address UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_step(inset_statement)== SQLITE_DONE)
{
long long lastRowId = sqlite3_last_insert_rowid(database);
NSString *rowId = [NSString stringWithFormat:#"%d", (int)lastRowId];
NSLog(#"Row ID of Last Inserted row %#",rowId);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return rowId;
}
if (sqlite3_exec(database, query, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
NSLog(#"Failed to Insert msg in message table Error = %s",errMsg);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return nil;
}
else
{
sqlite3_finalize(inset_statement);
}
}
NSLog(#"=============saveData Close==============");
sqlite3_close(database);
return nil;
}
You are not handling if there are any errors in the SQLite statements you are preparing.
The function will always return true because arrdata is never null
You need to add anelse statements to your
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK)
to show any errors...
NSLog(#"%s",sqlite3_errmsg(database));
- (IBAction)submit:(id)sender {
NSString *sql = [NSString stringWithFormat:#"INSERT INTO employeedetails('employee_name','employee_mailid','employee_username','employee_password')VALUES('%#','%#','%#','%#')",self.textname.text,self.textmailid.text,self.textusername.text,self.textpassword.text];
NSLog(#"%#The inserted values are",sql);
char *err;
if (sqlite3_exec(db,[sql UTF8String], NULL, NULL, &err)!=SQLITE_OK) {
sqlite3_close(db);
NSAssert(0,#"sdsadadsderererwrcould not update the tabel");
}
else{
NSLog(#"nbbbbbbbbbbbbtable updated");
}
}
-(void)selectfn
{
const char *sqlStatement = "SELECT * FROM employeedetails"; // Your Tablename
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[name removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[name addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
NSLog(#"The array value is %#",name);
}
}
sqlite3_finalize(compiledStatement);
sqlite3_close(db);
}
Already I have insert values into table...Now I want to fetch values from the table and want to store one nsarray and display into tableview....help me plz
You can create Model class something like this
Header file
#import "Model.h"
#implementation Model
#synthesize _firstValue ,_secondValue ;
#end
Implementation file
#import <Foundation/Foundation.h>
#interface Model: NSObject
{
NSString *_firstValue ;
NSString *_secondValue ;
}
#property (nonatomic,retain) NSString *_firstValue ;
#property (nonatomic,retain) NSString *_secondValue ;
#end
Now fetching data using below lines...
//Cretae a array to store values
NSMutableArray *retArr = [[NSMutableArray alloc]init];
if ([self dbOpen]) // check db is open
{
const char *sqlStatement = [YOUR_QUERY UTF8String];
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
while( sqlite3_step(statement) == SQLITE_ROW )
{
// used model to fill the set of data
Model *obj = [[Model alloc] init];
obj._firstValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
obj._secondValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
[retArr addObject:obj];
obj = nil;
}
}
else { NSLog( QRY_EXEC_ERROR, sqlite3_errmsg(database) ); } // excute if any error
sqlite3_finalize(statement); // finalizing
sqlite3_close(database); // clossing the DB
}
Finally use retArr which holds your DB values.....
I have created multiple tables in my database. And now I want insert data into those tables. How to insert multiple tables data can anyone help regarding this.
I have written this code for creating 1 table:
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO ATRG (id, name, language,imgurl) VALUES ( \"%#\",\"%#\",\"%#\",\"%#\")", ID, name, lang,imgUrl];
const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(_globalDataBase, insert_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Record Inserted");
} else { NSLog(#"Failed to Insert Record");
}
Try this I hope it would be helpful!! This is mine code for insert data
#import "Sqlitedatabase.h"
#implementation Sqlitedatabase
+(NSString* )getDatabasePath
{
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *DB;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *databasePath = [docsDir stringByAppendingPathComponent:#"myUser.db"];
NSFileManager *filemgr = [[NSFileManager alloc]init];
if ([filemgr fileExistsAtPath:databasePath]==NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath,&DB)==SQLITE_OK) {
char *errorMessage;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS users(ID INTEGER PRIMARY KEY AUTOINCREMENT,FIRSTNAME TEXT,LASTNAME TEXT,EMAILID TEXT,PASSWORD TEXT,BIRTHDATE DATE)";
if (sqlite3_exec(DB,sql_statement,NULL,NULL,&errorMessage)!=SQLITE_OK) {
NSLog(#"Failed to create the table");
}
sqlite3_close(DB);
}
else{
NSLog(#"Failded to open/create the table");
}
}
NSLog(#"database path=%#",databasePath);
return databasePath;
}
+(NSString*)encodedString:(const unsigned char *)ch
{
NSString *retStr;
if(ch == nil)
retStr = #"";
else
retStr = [NSString stringWithCString:(char*)ch encoding:NSUTF8StringEncoding];
return retStr;
}
+(BOOL)executeScalarQuery:(NSString*)str{
NSLog(#"executeScalarQuery is called =%#",str);
sqlite3_stmt *statement= nil;
sqlite3 *database;
BOOL fRet = NO;
NSString *strPath = [self getDatabasePath];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_DONE)
fRet =YES;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return fRet;
}
+(NSMutableArray *)executeQuery:(NSString*)str{
sqlite3_stmt *statement= nil; // fetch data from table
sqlite3 *database;
NSString *strPath = [self getDatabasePath];
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSInteger i = 0;
NSInteger iColumnCount = sqlite3_column_count(statement);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
while (i< iColumnCount) {
NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, (int)i)];
NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, (int)i)];
[dict setObject:str forKey:strFieldName];
i++;
}
[allDataArray addObject:dict];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return allDataArray;
}
#end
And called that method where you want to use!!
NSString *insertSql = [NSString stringWithFormat:#"INSERT INTO users(firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
if ([Sqlitedatabase executeScalarQuery:insertSql]==YES)
{
[self showUIalertWithMessage:#"Registration succesfully created"];
}else{
NSLog(#"Data not inserted successfully");
}
And If you want to fetch data from table then you can do this!!
NSString *insertSql = [NSString stringWithFormat:#"select emailid,password from users where emailid ='%#' and password = '%#'",[_usernameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],[_passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSMutableArray *data =[Sqlitedatabase executeQuery:insertSql];
NSLog(#"Fetch data from database is=%#",data);
Multiple Execute Query!!
NSString *insertSql = [NSString stringWithFormat:#"INSERT INTO users (firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
NSString *insertSql1 = [NSString stringWithFormat:#"INSERT INTO contact (firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:insertSql,insertSql1,nil];
for (int i=0; i<array.count; i++)
{
[Sqlitedatabase executeScalarQuery:[array objectAtIndex:i]];
}
See this for your issue:
Insert multiple tables in same database in sqlite
or if you want
Multi-table INSERT using one SQL statement in AIR SQLite
then use this:
http://probertson.com/articles/2009/11/30/multi-table-insert-one-statement-air-sqlite/
I've been reading all questions related to SQlite encoding with no success, so I'll try to ask about my specific case.
I have an iOS app with a SQLite database prepopulated.
This SQLite has been converted from a MySQL database.
Both the SQLite and MySQL databases have UTF8 enconding (the conversion process set the default sqlite enconding to UTF8)
If I open my sqlite database with Firefox SQlite Manager I can read all the content without problems, and all UTF8 chars are shown properly, so I guess everything was converted correctly.
But, when I try to perfom a select with UTF8 chars inside, the query fails.
This is the method where I perform the queries:
- (NSArray *)performQuery:(NSString *)query
{
static sqlite3 *db;
sqlite3_stmt *resultado;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"mydatabase.sqlite"];
const char *dbpath = [writableDBPath UTF8String];
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
printf("%s\n", [query UTF8String]);
int codigo = sqlite3_prepare_v2(db,[query UTF8String],[query length],&resultado,NULL);
if (codigo == SQLITE_OK)
{
NSMutableArray *result = [NSMutableArray array];
while (sqlite3_step(resultado) == SQLITE_ROW)
{
NSMutableArray *row = [NSMutableArray array];
for (int i = 0; i < sqlite3_column_count(resultado); i++)
{
int colType = sqlite3_column_type(resultado, i);
id value;
if (colType == SQLITE_TEXT)
{
value = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(resultado, i)];
if ([value isEqualToString:#"(null)"] || [value isEqualToString:#""] || (value == nil) || [value isKindOfClass:[NSNull class]])
{
value = #"";
}
}
else if (colType == SQLITE_INTEGER)
{
int col = sqlite3_column_int(resultado, i);
value = [NSNumber numberWithInt:col];
}
else if (colType == SQLITE_FLOAT)
{
double col = sqlite3_column_double(resultado, i);
value = [NSNumber numberWithDouble:col];
}
else if (colType == SQLITE_NULL)
{
value = [NSNull null];
}
else
{
NSLog(#"ERROR: DataBase - performQuery - Campo desconocido");
}
[row addObject:value];
}
[result addObject:row];
row = nil;
}
sqlite3_finalize(resultado);
sqlite3_close(db);
resultado = nil;
return result;
}
else
{
NSLog(#"ERROR [%d](%s): %#", codigo, sqlite3_errmsg(db), query);
}
}
else
{
NSLog(#"ERROR: No se pudo abrir la base de datos");
}
sqlite3_close(db);
db = nil;
resultado = nil;
return nil;
}
And this is the method where I call performQuery:
- (int) getIdForItem:(NSString *)item
{
NSString *query = [NSString stringWithFormat:#"SELECT item_id FROM table_items WHERE item_name=\"%#\"", item];
NSLog(#"QUERY:\n%#", query);
NSArray *answer = [self performQuery:query];
if([answer count] > 0)
return [[[answer objectAtIndex:0] objectAtIndex:0] intValue];
return -1;
}
If I make this call:
[self getIdForItem:#"Camión"];
This is the output:
QUERY:
SELECT item_id FROM table_items WHERE item_name="Camión"
SELECT item_id FROM table_items WHERE item_name="Camión"
ERROR [1](unrecognized token: ""Cami√≥n"): SELECT item_id FROM table_items WHERE item_name="Camión"
This error is produced in the method:
sqlite3_prepare_v2(db,[query UTF8String],[query length],&resultado,NULL)
So, Why is Camión interpreted as Cami√≥n in sqlite_prepare_v2? Both the query and the sqlite database are using UTF8, so I guess I'm missing something...
Well, the rmaddy's solution worked perfectly for me. What I've done is:
PerformQuery is almost the same, it receives a new argument:
- (NSArray *)performQuery:(NSString *)query withArgument:(NSString *)arg
Just after the sqlite3_prepare_v2 I've made the bind:
int codigo = sqlite3_prepare_v2(db,[query UTF8String],[query length],&resultado,NULL);
if (codigo == SQLITE_OK)
{
sqlite3_bind_text(resultado, 1, [arg UTF8String], -1, SQLITE_TRANSIENT);
NSMutableArray *result = [NSMutableArray array];
while (sqlite3_step(resultado) == SQLITE_ROW)
And finally, I call this method this way:
- (int) getIdForItem:(NSString *)item
{
NSString *query = #"SELECT item_id FROM table_items WHERE item_name=?1";
NSLog(#"QUERY:\n%#", query);
NSArray *answer = [self performQuery:query];
if([answer count] > 0)
return [[[answer objectAtIndex:0] objectAtIndex:0] intValue];
return -1;
}
I am new to iOS. I am trying to implement a SQLite database.
My problem is that when I go to fetch data from database, it takes a lot of time even though there are only 50 records inside the tables.
I did make a separate method for fetching data because many times I need to retrieve data for different tables.
My method:
-(NSArray*)fetch_data:(NSString *)table_name fields_arr:(NSMutableArray *)fields_arr{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"test.db"]];
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
sqlite3_stmt *SelectStatement;
NSMutableDictionary *record_dict;
NSString *SelectQry=#"select ";
NSString *lastField = [fields_arr lastObject];
for (int i =0; i<[fields_arr count]; i++) {
if (fields_arr[i] == lastField) {
SelectQry = [SelectQry stringByAppendingString:[NSString stringWithFormat:#"%# ",fields_arr[i]]];
} else {
SelectQry = [SelectQry stringByAppendingString:[NSString stringWithFormat:#"%#,",fields_arr[i]]];
}
}
SelectQry = [SelectQry stringByAppendingString:[NSString stringWithFormat:#"from %#",table_name]];
const char *query_stmt = [SelectQry UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &SelectStatement, NULL) == SQLITE_OK)
{
while(sqlite3_step(SelectStatement) == SQLITE_ROW)
{
record_dict=[[NSMutableDictionary alloc]init];
for (int i = 0; i<[fields_arr count]; i++) {
NSString *field_value = [[NSString alloc]init];
field_value = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(SelectStatement, i)];
[record_dict setValue:field_value forKey:fields_arr[i]];
}
[resultArray addObject:record_dict];
}
return resultArray;
//sqlite3_reset(statement);
sqlite3_finalize(SelectStatement);
}
else{
sqlite3_finalize(SelectStatement);
return nil;
}
}
In your code you are opening database connection for each time method is called for fetching data. This is not appropriate way. You must establish connection only once and use it.
+(sqlite3 *)openDatabase{
if (database == NULL) {
NSString* str_path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [str_path stringByAppendingPathComponent:strDatabaseName];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
NSLog(#"Database Successfully Opened");
}
else {
NSLog(#"Error in opening database");
database = NULL;
}
}
return database;}
You can call this on app launch from app delegate and define this method in a class where you are defining other DB methods. I hope it will reduce some overhead and will reduce some time too.