I made dbfile sample.db by terminal in advance, and added the file to the project.
But the App create a dbfile from scratch, instead of refering to the db added.
How do I need to fix to refer the db added?
NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString* dir = [paths objectAtIndex:0];
FMDatabase* db = [FMDatabase databaseWithPath:[dir stringByAppendingPathComponent:samble.db]];
[db open];
Check for the existence of the database in Documents folder before you try to open it, and if it's not there, then copy the version from the bundle to the Documents folder before subsequently opening it from the Documents folder.
So, first, because you have your blank database sitting in the Documents folder, remove it (by uninstalling the app and then re-installing). And then you can do something like the following
BOOL success;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* dir = [paths objectAtIndex:0];
NSString* documentsPath = [dir stringByAppendingPathComponent:#"samble.db"];
NSFileManager* fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:documentsPath]) {
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"samble" ofType:#"db"];
NSAssert(bundlePath, #"%s: database not found in bundle", __FUNCTION__);
NSError *copyError;
success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:©Error];
NSAssert(success, #"%s: copyItemAtPath failed: %#", __FUNCTION__, copyError);
}
FMDatabase* db = [FMDatabase databaseWithPath:documentsPath];
NSAssert(db, #"%s: databaseWithPath failed", __FUNCTION__);
success = [db open];
NSAssert(success, #"%s: open failed", __FUNCTION__);
Related
- (void) copyDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:ABC.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:ABC.Sqlite];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (success)
{
NSURL *url=[NSURL URLWithString:WSURL2];
} else
{
NSLog(#"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
I need to add any code for to View Sqlite File ??
I tried by adding these in Plist: UIFileSharingEnabled, CFBundleDisplayName
How can i view my SQLIte file in iTunes ?
Referred links:
How to enable file sharing for my app?, UIFileSharingEnabled has no effect
If i enabled iTunes file sharing option in my app to backup app data in PC, will appStore rejects the app ?
You are not creating the file in the Documents directory, but the Library directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
// ^^^^^^^^^^^^^^^^^^
You want NSDocumentDirectory.
when i use simulator,i can find the database file in /documents .but when i use my iPhone to run the project,i can not find the database file.
what time should i create the database file or use this code in my project?
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex:0];
NSString *dbFilePath = [documentFolderPath stringByAppendingString:DATABASENAME];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isExist = [fm fileExistsAtPath:dbFilePath];
if (!isExist) {
NSString *backupDbPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:DATABASENAME];
[fm copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];
}
For the first time or the database file does not exist in the documents directory, you have to copy DB file to document directory:
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}
}
Ref: http://www.appcoda.com/sqlite-database-ios-app-tutorial/
You can't access the directories of iPhone or iPad. So even if you successfully created a database, you won't see it. You can judge its existence by read data from it.
I am working with the sqlite database and everything is going well. I added 4 entries in the table, and then added textview on my xib file. Now i want that this data should be fetched from the sqlite database which is placed in the bundle of the project. But i am not getting how to call this database from the bundle to thedirectory path. Please help me out regarding this issue.
Use this code:
First call this method which will check wheter dbfile is stored in documents Directory or not. If not It will write your file to documents directory.
-(void)openDatabase {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"databasefilename.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
error:&error];
if (!success)
NSLog(#"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];
return [documentsDir stringByAppendingPathComponent:#"databasefilename.sqlite"];
}
Then check in Appdelegate or any other class where you want:
if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
NSLog(#"database opened successfully");
}
I am a newbie here. I am not able to insert any data into my SQLite database when running on my device. I am using the below piece of code to connect SQLite. It works perfect in my simulator but doesn't work on my iPad device. Can anyone help please? Thank you.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"DADatabase1.sqlite"];
NSLog(#"%#", writableDBPath);
FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];
/*if ([fileManager fileExistsAtPath:writableDBPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"DADatabase1.sqlite" ofType:#"sqlite"];
[fileManager copyItemAtPath:resourcePath toPath:writableDBPath error:nil];
}*/
[db open];
[db traceExecution];
[db beginTransaction];
BOOL success = [db executeUpdate:[NSString stringWithFormat:#"insert into PatientDetails (patAge) values (?)",patAge.text]];
if(!success)
{
NSLog(#"Query not success!");
}
else {
NSLog(#"Query success!");
}
//NSString *query = [NSString stringWithFormat:];
[db commit];
[db close];
Did you put your Database with your Tables in your Projects resources folder? You have to copy your database file to your Apps Document folder.
+ (BOOL)initDB {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"sqlite.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[ NSBundle mainBundle] pathForResource:#"sqlite" ofType:#"db"];
[fileManager copyItemAtPath:bundle toPath:path error:nil];
return YES;
}
return NO;
}
The sample code provided doesn't have a CREATE TABLE statement. The INSERT has nowhere to insert to. Did you create the table manually (using the sqlite3 command line tool) while you were developing in the simulator?
NOTE that:
File names in simulator is not case sensitive, but in device is case sensitive. Make sure your file name is exactly same.
I use sqlite and fmdb wrapper. My code for load db is this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"biscuit.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:path];
I add biscuit.sqlite to my project, but this code create new file instead open existing one. How can I load this file?
If you only want to read data from your database, try to use the code below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"biscuit" ofType:#"sqlite"];
If you need read/write access, you have to copy your database to a writable user folder first.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"biscuit.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"biscuit.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success) {
NSLog(#"Failed to create writable DB. Error '%#'.", [error localizedDescription]);
} else {
NSLog(#"DB copied.");
}
}else {
NSLog(#"DB exists, no need to copy.");
}