How can I get database path for creating database in iOS?
I know how to execute queries but I want first create database from document directory.
Try this
-(void)copyDatabaseIfNeeded
{
#try
{
NSFileManager *fmgr=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
dbPath=[path stringByAppendingPathComponent:#"Data.sqlite"];
if(![fmgr fileExistsAtPath:dbPath]){
NSString *defaultDBPath=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"Addict.sqlite"];
if(![fmgr copyItemAtPath:defaultDBPath toPath:dbPath error:&error])
NSLog(#"failure message----%#",[error localizedDescription]);
}
}
#catch (NSException *exception)
{
NSLog(#"Exception: %#", exception);
}
}
-(NSString *)getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"Data.sqlite"];
}
-(void)openDatabase
{
[self copyDatabaseIfNeeded];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
//Database Opened
NSLog(#"Database opened");
}
else
{
NSLog(#"Database cannot be opened");
}
}
-(void)closeDatabase
{
sqlite3_close(database);
}
Hope it helps you..
// Database handling
NSString *databaseFile = [[NSBundle mainBundle] pathForResource:#"DBname" ofType:#"sqlite"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *dbPath = [basePath stringByAppendingPathComponent:[NSString stringWithFormat:#"DBname.sqlite"]];
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:dbPath]){
[fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
}
maybe this will help you
Try this :
// Get data
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"dbFileName.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if(![filemgr fileExistsAtPath:databasePath])
{
NSData *content = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"dbFileName" ofType:#"db"] options:NSDataReadingMapped error:nil];
[content writeToFile:databasePath options:NSDataWritingAtomic error:nil];
}
Yes I got answer thank you.
//Here this may help you for select data from database
-(NSMutableDictionary*)SelectAllData
{
AppDelegate *AppDel=(AppDelegate *)[[UIApplication sharedApplication]delegate];
[AppDel checkAndCreateDatabase];
NSMutableArray *itemArray =[[[NSMutableArray alloc]init] autorelease];
if(sqlite3_open([AppDel.databasePath UTF8String],&database) == SQLITE_OK)
{
NSString *sql =[NSString stringWithFormat:#"Select *from table"];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSMutableDictionary *dicOfItem=[[NSMutableDictionary alloc]init];
[dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)] forKey:#"_id_article"];
[dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)] forKey:#"type"];
[dicOfItem setValue:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)] forKey:#"Id"];
[itemArray addObject:dicOfItem];
[dicOfItem release];
}
sqlite3_close(database);
}
}
else
sqlite3_close(database);
//Even though the open call failed, close the database connection to release all the memory.
NSMutableDictionary *dictresp = [NSMutableDictionary dictionaryWithObjectsAndKeys:itemArray,#"objects", nil];
return dictresp;
}
//Here this may help you for inserting data from database
- (void) insert_intable
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate checkAndCreateDatabase];
for(int i=0;i<[[articleDict objectForKey:#"objects"] count];i++)
{
if (sqlite3_open([[appDelegate databasePath] UTF8String], &database) == SQLITE_OK) {
insertStmt=nil;
if(insertStmt == nil) {
NSString *sqlTmp=[NSString stringWithFormat:#"Insert into table(Type,Category_id) Values('%#','%#')",articleType,catID];
const char *sqlStmt=[sqlTmp UTF8String];
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &insertStmt, NULL);
if (returnValue==SQLITE_OK) {
NSLog(#"Success");
} else {
NSLog(#"Unsuccess");
}
sqlite3_step(insertStmt);
sqlite3_finalize(insertStmt);
sqlite3_close(database);
}
}
}
}
use the following code to set your Sqlite path
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
databaseName=#"yourfileName.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
}
-(void) checkAndCreateDatabase {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
else
printf("NO File found");
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
Related
I don't know how to fix this error, I go to "Build Phases" and add sqlit.db file to Bundle resources but it still error.
Have anyone solve the problem this thing?.
Click Here to see code
-(void) initDatabase{
dbName = #"MBox_karaoke.db";
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writeableDBPath = [documentsDirectory stringByAppendingPathComponent:dbName];
success = [fileManager fileExistsAtPath:writeableDBPath];
if(success){
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writeableDBPath error:&error];
if (!success) {
// NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
NSLog(#"Database created failed, %#",[error localizedDescription]);
}
else {
NSLog(#"Database created successfully");
}
}
As an error states resource file not found.
Make sure you copied the database file in bundle. When you drag database to project navigator, make sure that you have checked "Copy item if needed".
Following solution working for me.
-(void)initializeDatabase {
NSError *error;
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [docPaths objectAtIndex:0];
NSString *docPath = [docDir stringByAppendingPathComponent:#"Test.sqlite"];
NSString *template_path = [[NSBundle mainBundle] pathForResource:#"Test" ofType:#"sqlite"];
if (![fm fileExistsAtPath:docPath])
[fm copyItemAtPath:template_path toPath:docPath error:&error];
//-====
}
Your code is correct but some time database file doesn't select target membership that your database doesn't copy your path that it's this type error occur.
First Remove/Uninstall your install app.
Please, Select your database file in xcode and see your target membership is check or uncheck. Uncheck that select check. (See below image)
Run the project simulator and check your database available in your path. Database available that see your database browse contain is correct.
NSLog("Path: %#",defaultDBPath);
My answer
+ (NSString *)databasePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sql_Path=[paths objectAtIndex:0];
NSString *dbPath=[sql_Path stringByAppendingPathComponent:#"MBox_karaoke.sqlite"];
NSFileManager *fileMgr=[NSFileManager defaultManager];
BOOL success;
NSError *error;
success=[fileMgr fileExistsAtPath:dbPath];
if (!success)
{
NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"MBox_karaoke.sqlite"];
success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
}
return dbPath;
}
Create Table and here My Table Name is Account
+ (void) createTableForAccount
{
char *error;
NSString *filePath =[self databasePath];
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *strQuery=[NSString stringWithFormat:#"CREATE TABLE IF NOT EXISTS Account(id TEXT,name TEXT);"];
sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
}
else
{
NSAssert(0, #"Table failed to create");
NSLog(#"Account Table Not Created");
}
sqlite3_close(database);
}
Insert Data
+ (void)insertAccountDetails:(NSString *)id:(NSString *)name
{
NSString *dbPath=[self databasePath];
if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
{
NSString *strQuery = [NSString stringWithFormat:#"INSERT into Account(id,name) values(?,?);"];
if(sqlite3_prepare_v2(database,[strQuery UTF8String] , -1, &stment, NULL)==SQLITE_OK)
{
sqlite3_bind_text(stment, 1, [[self checkEmpty:id] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stment, 2, [[self checkEmpty:name] UTF8String] , -1, SQLITE_TRANSIENT);
sqlite3_step(stment);
sqlite3_reset(stment);
}
sqlite3_finalize(stment);
}
sqlite3_close(database);
}
Fetch or Get Data from Table
+ (void)getAccountDetails
{
NSString *dbPath = [self databasePath];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat:#"SELECT id,name from Account"];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &stment, nil) == SQLITE_OK)
{
while (sqlite3_step(stment) == SQLITE_ROW)
{
NSString *idString = [[self charToString: (char *)sqlite3_column_text(stment, 0)]base64DecodedString];
NSString *nameString = [[self charToString: (char *)sqlite3_column_text(stment, 1)]base64DecodedString];
NSMutableArray *arrayId = [[NSMutableArray alloc]init];
NSMutableArray *arrayName = [[NSMutableArray alloc]init];
[arrayId addObject:idString];
[arrayName addObject:nameString];
}
sqlite3_reset(stment);
}
sqlite3_finalize(stment);
}
sqlite3_close(database);
}
Other Methods which called inside the db insert and fetch
insert
+ (NSString *)checkEmpty:(NSString *)check
{
if([check isEqual:[NSNull null]])
check = #" ";
return check;
}
Fetch method
+ (NSString*)charToString:(const char*)chart
{
NSString *string = #" ";
if(string)
{
chart = [self checkEmptyChar:chart];
string=[NSString stringWithUTF8String:chart];
}
return string;
}
+ (const char *)checkEmptyChar:(const char *)check
{
NSString *string = #" ";
if (check == NULL)
check = [string UTF8String];
return check;
}
In my app I am doing read ,write and delete on sqlite database(in db form) and it work fine in simulator but not working in actual device (giving error: No such table found).I try very hard to look for solution but couldn't find one or may be i misread something.
My db is in the
/users/My Name/library/developer/Core
simulator/devices/devicen-id/data/application/app-id/documents/My
database.
- (NSString *) getWritableDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:mydaatabase];
}
I am confuse where did i need to copy my database while running in the actual iOS device and what is the core problem.Any help regarding this will be very helpful
-(void)createEditableCopyOfDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:mydaatabase];
NSLog(#"=======%#", writableDBPath);
success = [fileManager1 fileExistsAtPath:writableDBPath];
if (success)
return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:mydaatabase];
NSLog(#"=======%#", [NSBundle mainBundle]);
success = [fileManager1 copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with Message : '%#'.",
[error localizedDescription]);
}
}
Check your .sqlite file is added to your Copy Bundle Resources in Build Phases of your project. If it is not there, add it in your project.
Moreover, I can't find code for opening the database. So, in your ViewController.h file, declare Sqlite *database;
In your ViewController.m file,
-(void)databaseOpen
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
NSString *myDBnew=[documentsDirectory stringByAppendingPathComponent:#"yourSqliteFile.sqlite"];
database =[[Sqlite alloc]init];
[database open:myDBnew];
NSLog(#"path: %#", myDBnew);
NSLog(#"Database opened");
}
and call it wherever you want as [self databaseOpen]; and then write your query.
Also, your -(void)createEditableCopyOfDatabaseIfNeeded should look something like this in your AppDelegate.m:
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"yourSqliteFile.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"yourSqliteFile.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Call -(void)createEditableCopyOfDatabaseIfNeeded in didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self createEditableCopyOfDatabaseIfNeeded];
return YES;
}
This should get you going.
Here are steps to working with SQLite Database.
Create your database in SQLite, add required table with well structure. and add it to your application.
Now, go to your app, select project from left panel, in middle panel -> General -> Linked Frameworks and Libraries(Last one) add libsqlite3.0.tbd (it is depend upon your Xcode version.)
Now, define below methods in your-object.h
#import <sqlite3.h>
+ (NSString *)getDBPath;
+ (void)copyDatabaseIfNeeded;
+ (void)openDatase;
Implement these in your-object.m
static sqlite3 *database;
#pragma mark - Copy and open databse
+ (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stirngByAppendingPathComponent:#"dbName.sqlite"];
}
+ (void)copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbName.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
+ (void)openDatase
{
NSString *dbPath = [self getDBPath];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"Database Successfully Opened.");
}
else
{
NSLog(#"Error in opening database.");
}
}
Then call method in AppDelegate.m in application: didFinishLaunchingWithOptions:
[DataManager copyDatabaseIfNeeded];
Whenever you want to perform task with database, open it and check.
For inserting in database
+ (void)insertData
{
const char *dbpath = [[self getDBPath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *strSQL = [NSString stringWithFormat:#"INSERT INTO table name………………."];
const char *insertQuery = [strSQL UTF8String];
sqlite3_stmt *insert_stmt;
if (sqlite3_prepare_v2(database, insertQuery, -1, &insert_stmt, NULL) == SQLITE_OK)
{
if (sqlite3_step(insert_stmt) == SQLITE_DONE)
{
// Code
}
else
{
NSLog(#"error");
}
}
sqlite3_finalize(insert_stmt);
sqlite3_close(database);
}
}
7. Completed.... enjoy with database.
I am fresher in iOS. I want to create database in my application. I am little bit confused regarding How I can able to create it ?
- (void)CreateDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"CabManagement.sqlite"];
success = [fileManager fileExistsAtPath:finalPath];
if(success)
{
NSLog(#"Database Already Created.");
return;
}
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"CabManagement.sqlite"];
success = [fileManager copyItemAtPath:defaultPath toPath:finalPath error:&error];
if(success)
{
NSLog(#"Database Created Successfully.");
}
}
- (void)InitializeDatabase
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"CabManagement.sqlite"];
if(sqlite3_open([finalPath UTF8String], &dbCabManagement) != SQLITE_OK)
{
sqlite3_close(dbCabManagement);
NSLog(#"Error to Open Database :- %s",sqlite3_errmsg(dbCabManagement));
}
}
Creating database programmatically
NSArray *dirPath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = dirPath[0];
NSString *databasePath = [[NSString alloc]initWithString:[docDir stringByAppendingPathComponent:#"YourDBName.db"]];
NSLog(#"the DB path:%#",databasePath);
NSFileManager *fileMgr =[NSFileManager defaultManager];
if ([fileMgr fileExistsAtPath:databasePath] == NO)
{
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &mydatabase) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt ="CREATE TABLE IF NOT EXISTS YourTableName (ID INTEGER PRIMARY KEY AUTOINCREMENT,Name Text,Age Text,Image Text,Location Text,Date Text,Time Text,MilliSecondsTime Text,Address Text)";
NSString *Status;
if (sqlite3_exec(mydatabase, sql_stmt, NULL, NULL, &errMsg))
{
Status =#"Failed to Create Table";
}
else
{
Status =#"Suucess in Create Table";
}
NSLog(#"%#",Status);
sqlite3_close(mydatabase);
}
else
{
Status =#"Failed to Open/Create Database";
NSLog(#"%#",Status);
}
}
Generally , I would like to use FMDB by ccgus to manage my database and there is no need for me to care about How to save the database.
NSString *path = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"db"];
FMDatabase *demoDB = [[FMDatabase alloc] initWithPath:path];
if(demoDB.open == NO) {
//Something is wrong when open the "demo.db" database
} else {
//Open the database success.Then you kan run some sql query in the database.
}
I am unable to create sqlite database in my documents directory.
Here is the code:
NSString *fileDir;
NSArray *dirPaths;
//Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask, YES);
fileDir = [dirPaths objectAtIndex:0];
// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:#"student.sql"]];
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 CONTACTS(ID INTEGER PRIMARY KEY , NAME TEXT, ADDRESS TEXT, MOBILE INTEGER)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
_status.text = #"Failed to create table";
}
sqlite3_close(database);
}
else
{
_status.text = #"Failed to open/create database";
}
}
I have debug the code and found that the compiler is not going under this condition.
sqlite3_open(dbPath, &database) == SQLITE_OK
I don't know what i am doing wrong.
Any help will be appreciated...
Thanks,
Check you code to get dirPath, you are getting right path or not, I used following way in my code and its working for me :
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// dirPaths = NSSearchPathForDirectoriesInDomains(NSDemoApplicationDirectory, NSUserDomainMask,YES);
fileDir = dirPaths[0];
// Build the database path
databasePath = [[NSString alloc]initWithString:[fileDir stringByAppendingPathComponent:#"student.sqlite"]];
this is how i managed it.
DataBaseAccess.m
static sqlite3 *database=nil;
-(id)init
{
if(self=[super init])
{
self.user_data=#"user_data.db";
}
return self;
}
-(void)createUserDataDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:user_data];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// construct database from external ud.sql
NSString *filePath=[[NSBundle mainBundle]pathForResource:#"ud" ofType:#"sql"];
NSString *sqlStatement=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(sqlite3_open([writableDBPath UTF8String], &database)==SQLITE_OK)
{
sqlite3_exec(database, [sqlStatement UTF8String], NULL, NULL, NULL);
sqlite3_close(database);
}
}
Your external sql file must contain the sql queries:
CREATE TABLE quantityInSubCountries (
refID INT,
quantity INT
);
CREATE TABLE quantityInSubRegions (
refID INT,
quantity INT
); ....
Hope it will help.
This is common methods used for Database
-(void)updateTable:(NSString *)tableName setname:(NSString *)Name setImagePath:(NSString *)imagePath whereID:(NSInteger)rid{
NSString *sqlString=[NSString stringWithFormat:#"update %# set name='%#' where id=%ld",tableName,Name,rid];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Faield to update");
}
else{
NSLog(#"update successfully");
}
}
-(void)deleteFrom:(NSString *)tablename whereName:(NSInteger )rid {
NSString *sqlString=[NSString stringWithFormat:#"delete from %# where id=%ld",tablename,(long)rid];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"faield to Delete");
}
else{
NSLog(#"Deleted successfully");
}
}
-(void)insertInTable:(NSString *)tableName withName:(NSString *)name withImagePath:(NSString *)imagePath
{
NSString *sqlString=[NSString stringWithFormat:#"insert into %#(name,path)values('%#','%#')",tableName,name,imagePath];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Failed to insert");
}
else{
NSLog(#"Inserted succesfully");
}
}
-(NSString *)path
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
return [documentDir stringByAppendingPathComponent:#"Storage.db"];
}
-(void)open{
if(sqlite3_open([[self path] UTF8String], &db)!=SQLITE_OK)
{
sqlite3_close(db);
NSLog(#"your database table has been crash");
}
else{
NSLog(#"Database open successfully");
}
}
-(void)closeDatabase
{
sqlite3_close(db);
NSLog(#"Database closed");
}
-(void)copyFileToDocumentPath:(NSString *)fileName withExtension:(NSString *)ext{
NSString *filePath=[self path];
NSFileManager *fileManager=[NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
NSString *pathToFileInBundle=[[NSBundle mainBundle] pathForResource:fileName ofType:ext];
NSError *err=nil;
BOOL suc=[fileManager copyItemAtPath:pathToFileInBundle toPath:filePath error:&err];
if (suc) {
NSLog(#"file copied successfully");
}
else
{
NSLog(#"faield to copied");
}
}
else
{
NSLog(#"File allready present");
}
}
-(NSMutableArray *)AllRowFromTableName:(NSString *)tableName{
NSMutableArray *array=[[NSMutableArray alloc] init];
NSString *sqlString=[NSString stringWithFormat:#"select *from %#",tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sqlString UTF8String], -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
Database *tempDatabase=[[Database alloc] init];
tempDatabase.Hid=sqlite3_column_int(statement, 0);
tempDatabase.Hname =[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
tempDatabase.Hpath=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
[array addObject:tempDatabase];
}
}
return array;
}
-(void)test
{
//Pet photos
NSString *sqlString=[NSString stringWithFormat:#"create table if not exists StorageTable(id integer primary key autoincrement,name text,path text)"];
char *error;
if (sqlite3_exec(db, [sqlString UTF8String], NULL, NULL, &error)!=SQLITE_OK) {
[self closeDatabase];
NSLog(#"Faield to blanck 1 %s",error);
}
else{
NSLog(#"Test On StorageTable Database successfully");
}
}
I want to copy my sqlite database from the database location with latest updates to my iOS application every time I launch the application.
Is there any way to do it?
you can add following methods to your appdelegate
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath
{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
//NSLog(#"dbpath : %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"database.sqlite"];
}
and call this method in your did finish with launching method
[self copyDatabaseIfNeeded]; hope this will help.
use below code for coping database when application launch
in your appdelegate.m
in
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self getdatabase];
return YES;
}
and add below function in to your appdelegate.m
-(void)getdatabase
{
BOOL success;
NSFileManager *filemanager = [NSFileManager defaultManager];
NSError *error;
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DBPath = [pathArray objectAtIndex:0];
NSString *writableDBPath = #"";
writableDBPath = [DBPath stringByAppendingPathComponent:#"xyz.sqlite"];
NSLog(#"writableDBPath:%#",writableDBPath);
success = [filemanager fileExistsAtPath:writableDBPath];
if (!success) {
NSString *defaultDBpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"xyz.sqlite"];
success = [filemanager copyItemAtPath:defaultDBpath toPath:writableDBPath error:&error];
if (!success) {
NSAssert(0, #"failed to copy database at path with message '%#'.",[error localizedDescription]);
}
}
NSLog(#"111writableDBPath:%#",writableDBPath);
}
Here it is in Swift 4/5
func copyDatabaseIfNeeded(sourcePath : String) -> Bool {
var destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
destPath = destPath + "/foo.db3"
let databaseExistsWhereNeeded = FileManager.default.fileExists(atPath: destPath)
if (!databaseExistsWhereNeeded) {
do {
try FileManager.default.copyItem(atPath: sourcePath, toPath: destPath)
print("db copied")
}
catch {
print("error during file copy: \(error)")
}
}
return true
}
try this one:
NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strDocDirectory = [docPath objectAtIndex:0];
self.strDatabasePath = [strDocDirectory stringByAppendingPathComponent:YOUR_DB];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: self.strDatabasePath ] == NO)
{
const char *dbpath = [self.strDatabasePath UTF8String];
sqlite3 *contactDB;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YOUR_Table (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(contactDB);
Try this in AppDelegate Class
.h file
#property(nonatomic, retain) NSString *dbPath;
.m file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self copyDatabaseIfNeeded];
}
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sampleDB.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
/********* Database Path *********/
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"sampleDB.sqlite3"];
}
It'll automatically copy, if it doesn't found any database in application.
Hopefully, it'll help you.
Thanks.
-(void)openDatase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.databasePath = [documentsDirectory stringByAppendingPathComponent:#"weightCal.sqlite"];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
}
-(void)dealloc{
sqlite3_close(database);
[super dealloc];
}
-(void)copyDatabase {
BOOL success;
NSFileManager *fileManager=[NSFileManager defaultManager];
NSError *error;
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager fileExistsAtPath:writablePath];
if(success) {
return;
}
NSString *defaultPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.sqlite"];
success=[fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
if(!success){
NSAssert1(0,#"Failed to create writable database file with message '%#' .",[error localizedDescription]);
}
}
Declare following teo variable in .h:
sqlite3 *database;
NSString *databasePath;