Reputation: 1919
I am trying to use Database SQLite in iOS. i have several questions in the following 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: @"calc.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_stmt =
"create table if not exists resultDetail (results integer)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(@"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(@"Failed to open/create database");
}
}
return isSuccess;
}
- (BOOL) saveData:(int)resultValue ;
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:@"insert into resultDetail (results) values (\"%d\")",resultValue];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_reset(statement);
return YES;
}
else
{
return NO;
}
// sqlite3_reset(statement);
}
sqlite3_reset(statement);
return NO;
}
- (int) findResult:(int)resultValue
{
int n=0;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"select results from resultDetail where results=\"%d\"",resultValue];
// NSString *querySQL = [NSString stringWithFormat:@"select * from resultDetail"];
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)
{
int n = sqlite3_column_int(statement, 0);
NSLog(@"%d let's see",n);
sqlite3_reset(statement);
return n;
}
else{
NSLog(@"Not found");
return 0;
} */
while(sqlite3_step(statement) == SQLITE_ROW){
n = sqlite3_column_int(statement, 0);
NSLog(@"%d is the value",n);
}
return n;
// sqlite3_reset(statement);
}
sqlite3_reset(statement);
}
sqlite3_reset(statement);
return 0;
}
-(BOOL)isEmpty{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"select * from resultDetail"];
// NSString *querySQL = [NSString stringWithFormat:@"select * from resultDetail"];
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){
sqlite3_reset(statement);
NSLog(@"Not Empty");
return NO;
}
}
sqlite3_reset(statement);
}
sqlite3_reset(statement);
return YES;
}
-(BOOL)isDuplicate:(int)resultValue{
BOOL n=NO;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"select results from resultDetail where results=\"%d\"",resultValue];
// NSString *querySQL = [NSString stringWithFormat:@"select * from resultDetail"];
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){
sqlite3_reset(statement);
n = YES;
}
sqlite3_reset(statement);
return n;
// sqlite3_reset(statement);
}
sqlite3_reset(statement);
}
sqlite3_reset(statement);
return NO;
}
@end
In above code, What is this
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
Is that class or method ?
Why are we creating getSharedInstance and what's the use of it?
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[ super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
What is NULL arguments in this, what we actually have to do with these?
sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK
I am new to ios so please correct me if i asked anything wrong. Thanks for the time (:
Upvotes: 0
Views: 264
Reputation: 564
You can save time and efforts if instead of "raw" C-based SQLITE API FMDB wrapper for Obj-C is used.
Look at https://github.com/ccgus/fmdb
Small example of code: I have Core Data entity which should be stored in SQLITE database with custom schema. This method is called on button tap (Mac OS X based, but no difference with IOS)
- (IBAction)saveProcessingButtonTapped:(id)sender
{
// Now we can create fresh database file and put there
// all data from our persistent store
FMDatabase *db = [FMDatabase databaseWithPath:fileToSave];
if (!db ) {
NSLog(@"Cannot create database!");
return;
}
if (![db open]) {
NSLog(@"Cannot open database at %@",fileToSave);
return;
}
// Create Table for data
NSString *schema = @"CREATE TABLE LOGDATA ( TIMESTAMP VARCHAR, SESSIONINDEX INTEGER, EVENT VARCHAR, DESCRIPTION VARCHAR, VERSION VARCHAR , PLATFORM VARCHAR, DEVICE VARCHAR, USERID VARCHAR, PARAMETERS VARCHAR, TIMEINSECS TIMESTAMP)";
BOOL created = [db executeStatements:schema];
if (!created) {
NSLog(@"Cannot create table!");
}
// Now we just copy with insert all data from CoreDatastoage to fresh database
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:[[SQLITE class] description]];
NSError *error = nil;
NSArray *result = [self.managedObjectContext executeFetchRequest:req error:&error];
if (!result && error) {
NSAlert *alert = [NSAlert alertWithError:error];
[alert runModal];
return;
}
for (SQLITE *record in result) {
NSDictionary *arguments = @{
@"SESSIONINDEX": record.sessionIndex,
@"TIMESTAMP": record.timestamp,
@"DEVICE": record.device,
@"EVENTDESCRIPTION": record.eventDescription,
@"NOTE" : (record.note ? record.note : @""),
@"PARAMETERS" : record.parameters,
@"PLATFORM" : record.platform,
@"USERID" : record.userID,
@"VERSION" : record.version,
@"DATESTRING" : record.dateString,
};
BOOL success = [db executeUpdate:@"INSERT INTO LOGDATA (SESSIONINDEX, TIMEINSECS, DEVICE, EVENT, DESCRIPTION, PARAMETERS, PLATFORM, USERID, VERSION, TIMESTAMP ) VALUES (:SESSIONINDEX, :TIMESTAMP, :DEVICE, :EVENTDESCRIPTION, :NOTE, :PARAMETERS, :PLATFORM, :USERID, :VERSION, :DATESTRING)" withParameterDictionary:arguments];
if (!success) {
NSLog(@"error = %@", [db lastErrorMessage]);
}
}
[db close];
self.informLabel.stringValue = @"Export completed";
NSLog(@"\n\n\n CoreDataDatabase is stored - %@", self.sqliteBaseFilename.stringValue);
NSLog(@"\n Exported database is stored in - %@",fileToSave);
}
Upvotes: 0
Reputation: 547
It is too long answer so Please go through this tutorials you can understand the how to SQLite work in iOS
http://www.appcoda.com/sqlite-database-ios-app-tutorial/
Upvotes: 1