mardi 4 août 2015

iOS insert into SQLite db failing

The app should open the database, check for existing States, load those into a list view (This part works, even though it kicks out the "That did not work" string). Then the user is presented with a UI Screen with text fields to input the State name, capital, and population. It should write to the database at this point, and then display the updated list view. The data is not being written to the database apparently, although it is persisting in some form. Please look over the following code and see if there is anything glaringly obvious with it and point me in the right direction.

Database: States.sqlite (I have tried .db and .sql as well and also failed)

#import "SQLiteDataModel.h"
#import "State.h"

@implementation SQLiteDataModel

-(NSString *)databasePathInResources
{
// Create an instance of NSBundle that points to the main bundle.
NSBundle *bundle = [NSBundle mainBundle];

// Create an instance of NSString the points to the file path of the database within the bundle.
NSString *dbPath = [bundle pathForResource:@"States" ofType:@"sqlite"];

// Return the dbPath string.
return dbPath;
}

-(NSString *)databasePathInDocuments
{
// Get an array of paths within the document directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

// Get the path at index 0 of the array and append path component States.db.
NSString *pathAtIndex = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"States.sqlite"];

// Return the pathAtIndex.
return pathAtIndex;
}

-(void)copyFileFrom:(NSString *)fromPath toPath:(NSString *)toPath
{
// Check if file exists in resources.
NSFileManager *fileManager = [NSFileManager defaultManager];

BOOL fromExists = [fileManager fileExistsAtPath:fromPath];

if(fromExists != YES)
{
    NSLog(@"Something is wrong. The database file does not exist in resources.");

    return;
}

NSError *error = nil;


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *writableDbPath = [documentDirectory stringByAppendingPathComponent:@"States.sqlite"];
BOOL success = [fileManager fileExistsAtPath:writableDbPath];

if(!success)
{
    NSString *defaultDbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"contacts.sqlite"];
    success = [fileManager copyItemAtPath:defaultDbPath toPath:writableDbPath error:&error];
    if (!success)
    {
        NSLog(@"That did not work!");
    }
}
}

-(id)init
{
self = [super init];

if(self)
{
    [self copyFileFrom:[self databasePathInResources] toPath:[self databasePathInDocuments]];
}

// Create an instance of NSString that points to the string returned from databasePathInDocuments.
NSString *databaseWritablePath = [self databasePathInDocuments];

// Convert an NSString into a c string.
const char *c = [databaseWritablePath cStringUsingEncoding:NSUTF8StringEncoding];

// Open the database
int status = sqlite3_open(c, &databaseHandler);

if(status == SQLITE_OK)
{
    NSLog(@"Database opened successfully.");
}

else
{
    NSLog(@"Failed to open database.");
}

return self;
}

-(NSArray *)getStates
{
NSMutableArray *mutableState = [[NSMutableArray alloc]init];

const char *query = "select * from States";

sqlite3_stmt *statement;

int status = sqlite3_prepare_v2(databaseHandler, query, -1, &statement, NULL);

if(status == SQLITE_OK)
{
    NSLog(@"Query prepared successfully.");

    // Loop through the results and add them to the array.
    while(sqlite3_step(statement) == SQLITE_ROW)
    {
        const char *Name = (const char *)sqlite3_column_text(statement, 1);
        const char *stateCapital = (const char *)sqlite3_column_text(statement, 2);
        const char *statePopulation = (const char *)sqlite3_column_text(statement, 3);

        State *newState = [[State alloc]init];

        newState.stateName = [[NSString alloc]initWithCString:Name encoding:NSUTF8StringEncoding];
        newState.capital = [[NSString alloc]initWithCString:stateCapital encoding:NSUTF8StringEncoding];
        newState.population = [[NSString alloc]initWithCString:statePopulation encoding:NSUTF8StringEncoding];

        [mutableState addObject:newState];

    }
}

else
{
    NSLog(@"Failed to prepare query.");
    return nil;
}

return mutableState;
}

-(void)createState:(State *)newState
{

NSString *insertString = [[NSString alloc]initWithFormat:@"INSERT INTO States (\"name\", \"capital\", \"population\") VALUES (\"%@\", \"%@\", \"%@\");", newState.stateName, newState.capital, newState.population];
NSLog(@"%@", insertString);

const char *cQuery = [insertString cStringUsingEncoding:NSUTF8StringEncoding];

sqlite3_stmt *statement;

int status = sqlite3_prepare_v2(databaseHandler, cQuery, -1, &statement, NULL);


if(status == SQLITE_OK)
{
    NSLog(@"Prepared insert query.");
}

else
{
    NSLog(@"Failed to prepare insert query.");
}

status = sqlite3_step(statement);

if(status == SQLITE_OK)
{
    NSLog(@"Successfully inserted state into database.");
}

else
{
    NSLog(@"Failed to insert State into database.");
}
}


-(void)deleteState:(NSString *)name
{
NSArray *states= [self getStates];
NSMutableArray *mutableStates = [states mutableCopy];

NSString *query = [[NSString alloc]initWithFormat:@"delete from States where name='%@'", name];
const char *cQuery = [query cStringUsingEncoding:NSUTF8StringEncoding];
[mutableStates writeToFile:[self databasePathInDocuments] atomically:YES];

//create a statement object
sqlite3_stmt *statement;
int status = sqlite3_prepare_v2(databaseHandler, cQuery, -1, &statement, NULL);

if(status == SQLITE_OK)
{
    NSLog(@"Prepared delete query");
}

else
{
    NSLog(@"Failed to prepare delete query");
}

//execute the query
status = sqlite3_step(statement);
[mutableStates removeObject:name];

if(status == SQLITE_OK)
{
    NSLog(@"successfully deleted state from database");
    //remove the state from the array at a given index
}

else
{
    NSLog(@"Failed to delete state from database");
}
}
@end

The output is as follows:

2015-08-04 22:15:30.977 Database Application[923:20261] That did not work!
2015-08-04 22:15:30.979 Database Application[923:20261] Database opened    successfully.
2015-08-04 22:15:30.980 Database Application[923:20261] Query prepared successfully.
2015-08-04 22:16:13.480 Database Application[923:20261] That did not work!
2015-08-04 22:16:13.481 Database Application[923:20261] Database opened successfully.
2015-08-04 22:16:13.481 Database Application[923:20261] INSERT INTO States ("name", "capital", "population") VALUES ("Arkansas", "Little Rock", "34234234");
2015-08-04 22:16:13.481 Database Application[923:20261] Prepared insert query.
2015-08-04 22:16:13.490 Database Application[923:20261] Failed to insert State into database.
2015-08-04 22:16:13.491 Database Application[923:20261] Query prepared successfully.

Aucun commentaire:

Enregistrer un commentaire