I need code review about database access
I don't use CoreData as I like to use self written code for database access.
I need that someone revise my code so that I know that I am don't doing
anything wrong here.
I use sqlite for all CRUD operations and it works fine I just want to be
sure that this is the right way: I have this function in my
DataBaseAccessController
-(void)initializeDatabase
{
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory
stringByAppendingPathComponent:@"mobile_log.db"];
bool databaseAlreadyExists = [[NSFileManager defaultManager]
fileExistsAtPath:databasePath];
if (sqlite3_open([databasePath UTF8String], &databaseHandle) ==
SQLITE_OK)
{
if (!databaseAlreadyExists)
{
// create all tables here
}
// check to see if I need to update database structure
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int databaseVersion = [[defaults objectForKey:@"databaseVersion"]
intValue];
}
}
- (void)dealloc {
sqlite3_close(databaseHandle);
}
Every time when I need to make something with database (in all parts of my
code) I use it like this:
DataBaseAccessController* d = [[DataBaseAccessController alloc] init];
... some function
[d initializeDatabase];
[d getSomethingFromDatabase]; // in each of this function at the end
before return data I have sqlite3_finalize(statement);
... some other function
[d initializeDatabase];
[d saveSomethingToDatabase];
... some other function
[d initializeDatabase];
[d deleteSomethingFromDatabase];
etc.
I it ok to call my initialize function each time or this is completely wrong?
Also you can see I have databaseVersion variable.
When I need to make update to the new version of app I check what is in
this variable and base on that I alter my database for new things. Is this
valid way?
No comments:
Post a Comment