ios Sqlite connectivity - ios

my problem is that i am trying to connect my database to sqlite . it always with an error "table not found".. what should i do now .. plz help
here is my code for opendatabaseconnectivity....
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
BOOL executeQueryResults = sqlite3_step(compiledStatement);
if (executeQueryResults == true) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(#"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
}
// Close the database.
sqlite3_close(sqlite3Database);
}

Before accessing your database, have you copied it into document directory ?
Like this :
static sqlite3 *database = nil;
+ (void)openDatabase
{
[self copyDatabaseIfNeeded];
(sqlite3_open([[self getDBPath] UTF8String],&database));
}
+ (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSLog(#"%#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"databaseName.sqlite"];
}
+ (void)copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
NSLog(#"dbpath=%#",dbPath);
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"databaseName.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message \"%#\".", [error localizedDescription]);
}
}
Also check that the table which you are going to access is created in database before use.

Related

iOS objective c data is not saving in sqlite3 database

[[NSString alloc]initWithString:[self.documentsDirectory stringByAppendingPathComponent:#"cartdb.sql"]];
Data is not saving in sqlite3 database. BOOL openDatabaseResult is showing no and sqlite3 database is showing null
The query :
query = [NSString stringWithFormat:#"insert into cartProductInfo(null, '%#', '%#', %d)", self.information.text, #"productid", [self.priceDisplayLabel.text intValue]
The code of db
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [[NSString alloc]initWithString:[self.documentsDirectory stringByAppendingPathComponent:#"cartdb.sql"]];
// Initialize the results array.
if (self.arrResults != nil) {
[self.arrResults removeAllObjects];
self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];
// Initialize the column names array.
if (self.arrColumnNames != nil) {
[self.arrColumnNames removeAllObjects];
self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
BOOL executeQueryResults = sqlite3_step(compiledStatement);
if (executeQueryResults == SQLITE_DONE) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(#"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
}
// Close the database.
sqlite3_close(sqlite3Database);
}

How to close database in sqlite in ios?

I am using SqliteDatabase in my project.I am calling a function for data manuplation.
-(void)updateInspectionMapData2:(NSString *)clientid : (NSString *)inspectionid : (NSString *)status
{
NSLog(#"EIGHT");
NSLog(#"inside update data");
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSArray *checkVal = [self getSubClientDataByInspectionId:inspectionid :clientid];
NSLog(#"check is %#",checkVal);
if(checkVal == nil || [checkVal count] == 0)
{
NSString *querySql=[NSString stringWithFormat:
#"UPDATE inspectioninspectormap SET status=\"%#\" where inspectionid = \"%#\" and clientid =\"%#\" and (status = \"1\" or status = \"2\")",status,inspectionid,clientid];
NSLog(#"sql is %#",querySql);
const char *sql=[querySql UTF8String];
if(sqlite3_prepare_v2(database,sql, -1, &statement, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(statement))
{
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(database));
}
else
{
sqlite3_reset(statement);
NSLog(#"Update done successfully!");
}
}
sqlite3_finalize(statement);
}
}
sqlite3_close(database);
}
Please tell me is this the right way to close sqlite database.I am not sure i am right because later i get error unable to open database.?
There are many problems with your code. Here's what I see after just a quick glance:
You try to close the database even if it doesn't open.
You try to finalize the prepared statement even if the statement can't be prepared.
You needlessly call sqlite3_reset on the prepared statement.
You build your query using stringWithFormat: instead of properly binding values into the prepared statement.
You are using sqlite3_open instead of sqlite3_open_v2.
You don't log an error if sqlite3_open or sqlite3_prepare_v2 fail.
There is an issue in your code:
This code:
}
sqlite3_finalize(statement);
}
}
sqlite3_close(database);
should be changed to:
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
Closing the sqlite should happen right after you finish your work with database, and also within the open connection if loop, but not after the open connection!!!!
When using sqlite, opening and closing should be taken care, else it could lead to lock the database. The problem occurs when you try to open another connection to sqlite without closing the previous one, then your database will be locked .To avoid this, you need make sure that every open connection should have the close connection at the end.
You can try FMDB which is an sqlite wrapper. By using the FMDB,you can simply create the sqlite database using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"database.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
and you can open the database connection by:
[database open];
and close it by:
[database close];
and to execute a simple statement:
[database executeUpdate:#"create table user(name text primary key, age int)"];
There is a good tutorial out there:
+ (NSString*)setupDatabase
{
NSError *error;
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *dbFilePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", DATABASENAME, DATABASETYPE]];
if (! [[NSFileManager defaultManager] fileExistsAtPath:dbFilePath])
{
// if installing the application very first time didn't find db, need to copy
NSString *backupDbPath = [[NSBundle mainBundle] pathForResource:DATABASENAME
ofType:DATABASETYPE];
BOOL copiedBackupDb = [[NSFileManager defaultManager] copyItemAtPath:backupDbPath
toPath:dbFilePath
error:&error];
if (! copiedBackupDb)
{
// copying backup db failed
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
return nil;
}
}
return dbFilePath;
}
+ (NSString *)getDataBaseFilePath
{
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbFilePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", DATABASENAME, DATABASETYPE]];
return dbFilePath;
}
+(NSString*)selectItem:(NSString*)itemID
{
NSString *name=nil;
NSString* _dataBasePath = [self getDataBaseFilePath];
sqlite3 *database;
if (sqlite3_open([_dataBasePath UTF8String], &database) == SQLITE_OK) {
NSString *query;
query= [NSString stringWithFormat:#"select ITEM_id from Table where IF ITEM_id='%#' ",itemID];
const char *sql=[query UTF8String];
sqlite3_stmt *selectstmt;
if (sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL)==SQLITE_OK) {
while (sqlite3_step(selectstmt)==SQLITE_ROW) {
if (sqlite3_column_text(selectstmt, 0))
name=[NSString stringWithUTF8String:(char*) sqlite3_column_text(selectstmt, 0)];
}
sqlite3_finalize(selectstmt);
}
}
sqlite3_close(database);
return (name) ;
}
+(BOOL)updateITEM:(ItemObj*)itemObj;
{
NSString* _dataBasePath = [self getDataBaseFilePath];
sqlite3 *database;
if (sqlite3_open([_dataBasePath UTF8String], &database) == SQLITE_OK) {
NSString *qs=[NSString stringWithFormat:#"UPDATE ITEM set User_ID = '%#',User_Name = '%#',Item_id = '%#',User_Status = '%#' WHERE Item_id = '%#'", itemObj.usersid, itemObj.user_name, itemObj.user_id, itemObj.user_status, itemObj.user_id];
const char *sql=[qs UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) != SQLITE_OK)
return FALSE;
int result = sqlite3_step(selectstmt);
if(result != SQLITE_DONE) return FALSE;
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return TRUE;
}

overreleased while already deallocating Erro when trying to remove object from an array

-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Initialize the results array.
if (self.arrResults != nil) {
//if(self.arrResults.count>0)
[self.arrResults removeAllObjects];
self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];
// Initialize the column names array.
if (self.arrColumnNames != nil) {
[self.arrColumnNames removeAllObjects];
self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}else{
//added by keerti
[arrDataRow addObject:#""];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
bool done = sqlite3_step(compiledStatement) == SQLITE_DONE;
if (done) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(#"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(#"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
}
// Close the database.
sqlite3_close(sqlite3Database);
}
Above is the function to execute query passed to it. I call it from multiple classes but some time when i call [self.arrResults removeAllObjects] results to app crash. Can anyone guide how to handle the scenario.Any help will be appreciated.

Failing to Update/Delete record in Sqlite from IOS App

I'm creating an iPhone App which uses Sqlite to persist data,While i do insert/select operations the code works fine,but for update /delete operations code gets failed.
I found some links n stacker flow reg the same and some how i fixed SQLITE_BUSY Error using BEGIN Transaction and Commit statements surrounded my update/delete statements.Now if I execute he Update/delete statements,it returns SQLITE_OK :0 : Successful results.Also embedding the code here.I request the developers to please let me know where i went wrong.
For testing purpose I hardcoded the values like
"update drug set drugdose='2' where drugid=1".
After exe the statement it returns SQLITE_OK,but if I check the Database, the values are not getting updated.
enclosing two approaches i followed.
(BOOL )updateDrugDetails:(DrugDetails *)drugDetails{
BOOL *status=TRUE;
NSString *databasePath;
sqlite3 *database ;
NSString *docsDir;
NSArray *dirPaths;
sqlite3_stmt *updateStatement;
BOOL statusUpdate;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: #"drugdb2.sqlite"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSLog(#"databasePath %#",databasePath);
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
NSLog(#"Failed to open/create database");
isSuccess = NO;
}
else
{
isSuccess = YES;
NSLog(#"Able to open/create database");
}
if(isSuccess)
{
NSInteger drugID= [drugDetails drugId];
NSString *drugDose= [drugDetails drugDose];
NSString *drugStartDate= [drugDetails drugStartDate];
NSString *drugEndDate= [drugDetails drugEndDate];
const char *dbpath = [databasePath UTF8String];
NSString *temp=[NSString stringWithFormat:#"%d", drugID];
int tempInt=[temp integerValue];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
/*
// First Approach
*updateSQL =
[NSString stringWithFormat:
#"update drug set drugdose=?,drugstartdate=? ,drugenddate=?
where drugid =?"];
const char *update_stmt = [updateSQL UTF8String];
const char *drgDose = [drugDose UTF8String];
const char *drgStartDate = [drugStartDate UTF8String];
const char *drgEndDate= [drugEndDate UTF8String];
sqlite3_prepare_v2(database, update_stmt,-1, &updateStatement, NULL);
// sqlite3_bind_text(updateStmt, 4, [name.text UTF8String],
-1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStatement, 1, drgDose,-1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStatement, 2, drgStartDate,-1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStatement, 3, drgEndDate,-1,SQLITE_TRANSIENT);
sqlite3_bind_int(updateStatement, 4, tempInt);
sqlite3_busy_timeout(database, -1);
int updtStatus;
updtStatus=sqlite3_step(updateStatement);
if (updtStatus == SQLITE_DONE)
{
NSLog(#"Drug Details Updated with Status and rem Count");
statusUpdate= YES;
}else
{
NSLog(#"Failed to Update Drug Deatils with Status
rem Count%d",updtStatus);
statusUpdate= NO;
}
if(statusUpdate==TRUE)
{
NSLog(#"drug updated");
status=TRUE;
// sqlite3_reset(updateStatement);
sqlite3_finalize(updateStatement);
sqlite3_close(database);
database=nil;
databasePath=nil;
updateStatement=nil;
databasePath =nil;
}
else
{
NSLog(#"Error: %d", statusUpdate);
status=FALSE;
// sqlite3_reset(updateStatement);
sqlite3_finalize(updateStatement);
sqlite3_close(database);
database=nil;
databasePath=nil;
updateStatement=nil;
databasePath =nil;
}
sqlite3_finalize(updateStatement);
sqlite3_close(database);
*/
// Second Approach ,Inspite of hardcoding the values for testing purpose,its not updating //in DB.
NSString *replaceStatement =
[NSString stringWithFormat:#"update drug set
drugdose='2',drugstartdate='10/10/10',drugenddate='10/10/10' where drugid=1"];
char *error;
int updateStatus;
// sqlite3_busy_timeout(database, -1);
NSString *begTxn=#"BEGIN TRANSACTION;";
NSString *commit=#"COMMIT;";
sqlite3_exec(database,[begTxn UTF8String],NULL,NULL,&error);
updateStatus= sqlite3_exec(database,
[replaceStatement UTF8String], NULL, NULL, &error);
// Here the updatStatus returns 0 ,i.e sqlite Success Operatiion
sqlite3_exec(database,[commit UTF8String],NULL,NULL,&error);
if ((updateStatus == 0))
{
NSLog(#"Drug Details updated");
sqlite3_close(database);
}
else
{
NSLog(#"Error while Updating Drug Details %s", error);
sqlite3_close(database);
}
}
else
{
NSLog(#"Failed to Open Dtabase");
status=FALSE;
}
}else
{
NSLog(#"Failed to get the DB Path");
status=FALSE;
}
return status;
}

cannot insert value to sqlite DB iOS

Well following this tutorial I have some problems in inserting values to my DB although everything seems to be working fine.
This is my code for inserting entries.
-(void)insertOrder:(MyOrderList*)entry
{
// Create insert statement for the person
NSString *insertStatement = [NSString stringWithFormat:#"INSERT INTO LIST (URL, CODE, EMAIL, FULL) VALUES (\"%#\", \"%#\", \"%#\",\"%#\")", entry.db_url, entry.db_code, entry.db_email,entry.db_full];
NSLog(#"SQL INSERTION COMMAND:%#",insertStatement);
char *error;
if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Order inserted.");
}
else
{
NSLog(#"Error: %s", error);
}
}
And I can see "Order Inserted" being printed out.
This is my code for retrieving the list.
-(NSArray*) getList
{
NSMutableArray *persons = [[NSMutableArray alloc]init];
NSString *queryStatement = [NSString stringWithFormat:#"SELECT URL,CODE ,MAIL, FULL FROM LIST"];
sqlite3_stmt *statement;
NSLog(#"Query:%#",queryStatement);
if (sqlite3_prepare_v2(databaseHandle, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
// Iterate over all returned rows
while (sqlite3_step(statement) == SQLITE_ROW) {
NSLog(#"Url of my List is:%#",[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)]);
MyOrderList *person = [[MyOrderList alloc]initWithUrl:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)] andCode:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)] andEmail:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 2)] andFull:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 3)]];
[persons addObject:person];
// Release the person because the array takes ownership
//[person release];
}
sqlite3_finalize(statement);
}
//return [persons autorelease];
return persons;
}
and this is how I use it in my .m file
DataController *dataController = [[DataController alloc]init];
[dataController initDatabase];
//[dataController release];
MyOrderList *order = [[MyOrderList alloc] initWithUrl:url_2 andCode:keycode andEmail:mail andFull:full_2 ];
[dataController insertOrder:order];
//data has been added
NSMutableArray* persons = [dataController getList];
and I see that persons are 0.
From terminal I see this:
Admins-MacBook-Air:~ admin$ sqlite3 Users/admin/Library/Application\ Support/iPhone\ Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
Error: unable to open database "Users/admin/Library/Application Support/iPhone Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db": unable to open database file
Admins-MacBook-Air:~ admin$
it's like my db is not even created.
this is my code for creating the DB.
-(void)initDatabase
{
// Create a string containing the full path to the sqlite.db inside the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"sqlite.db"];
NSLog(#"Path is:%#",databasePath);
// Check to see if the database file already exists
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];
// Open the database and store the handle as a data member
if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
{
// Create the database if it doesn't yet exists in the file system
if (!databaseAlreadyExists)
{
// Create the PERSON table
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, URL TEXT, CODE TEXT, EMAIL TEXT, FULL TEXT)";
char *error;
if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Database and tables created.");
}
else
{
NSLog(#"Error: %s", error);
}
}
}
}

Resources