I am trying to to make a connection to a database and I'm finding that it is successful when I make the path go to NSBundle, but not when I try make the path be in my app's documents directory. Here is my code:
-(IBAction)setInput:(id)sender
{
NSString *strStoreNumber;
NSString *strRegNumber;
strStoreNumber = StoreNumber.text;
strRegNumber = RegNumber.text;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths lastObject];
NSString* databasePath = [documentsDirectory stringByAppendingPathComponent:#"tblStore.sqlite"];
// NSString* databasePath = [[NSBundle mainBundle] pathForResource:#"tblStore" ofType:#"sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"Opened sqlite database at %#", databasePath);
sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS tblStore (ID INTEGER PRIMARY KEY AUTOINCREMENT, Message TEXT)", NULL, NULL, NULL);
//...stuff
}
else
{
NSLog(#"Failed to open database at %# with error %s", databasePath, sqlite3_errmsg(database));
sqlite3_close (database);
}
//
NSString *querystring;
// create your statement
querystring = [NSString stringWithFormat:#"SELECT strStore, strReg FROM tblStore WHERE strStore = %# AND strReg = %#;", strStoreNumber, strRegNumber];
const char *sql = [querystring UTF8String];
NSString *szStore = nil;
NSString *szReg = nil;
sqlite3_stmt *statement = nil;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL)!=SQLITE_OK) //queryString = Statement
{
NSLog(#"sql problem occured with: %s", sql);
NSLog(#"%s", sqlite3_errmsg(database));
}
else
{
// you could handle multiple rows here
while (sqlite3_step(statement) == SQLITE_ROW)
{
szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
}
}
sqlite3_finalize(statement);
lblStoreNumber.text = szStore;
lblRegNumber.text = szReg;
//
}
I commented out the line:
NSString* databasePath = [[NSBundle mainBundle] pathForResource:#"tblStore" ofType:#"sqlite"];
When this line is NOT commented out, and the lines above it ARE commented out:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths lastObject];
NSString* databasePath = [documentsDirectory stringByAppendingPathComponent:#"tblStore.sqlite"];
Then it works fine. However, if those three lines are not commented out (as shown in the setInput method, then I get the following errors:
2012-05-07 13:44:29.511 CCoDBTry[1981:f803] Opened sqlite database at /Users/Matt****/Library/Application Support/iPhone Simulator/5.1/Applications/5DB7A218-A0F6- 485F-B366-91FD2F9BC062/Documents/tblStore.sqlite
2012-05-07 13:44:29.545 CCoDBTry[1981:f803] sql problem occured with: SELECT strStore, strReg FROM tblStore WHERE strStore = 8053 AND strReg = 4;
2012-05-07 13:44:29.546 CCoDBTry[1981:f803] no such column: strStore
Keep in mind, this same database table is accessed and works just fine when I use the NSBundle logic. I admit I don't fully understand the difference between NSBundle and documentsDirectory, but I think I would want my table to exist in my app's documents. I would greatly appreciate any help on this.
Thanks!
NSBundle is used to access resources within your application itself: that is, everything inside YourApp.app. The documentsDirectory is a location outside of your app -- it's in the "home directory" which is part of your app sandbox, and which is analogous to your user home directory on the Mac.
These are different locations, so using one to find a file at the same subpath of another won't work.
What #rickster is saying is this:
If you add the sqlite database to your project in Xcode, the database's file gets added to your app's bundle.
If you create the database in code, the file will (most likely) get created in your documents directory (but surely not in your bundle).
The two locations are completely separate. Your bundle is created when your app is compiled and cannot be changed later. Your documents directory is "sandboxed", which allows you access to it; you can read/write/delete files here.
Copy from NSBUndle TO NSDocumentDirectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"culinary-Info.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"culinary-Info" ofType:#"sqlite"];
[fileManager copyItemAtPath:bundle toPath:path error:nil];
}
Related
Ok so I have a database in my iPhone simulator documents. And I now know for sure it's in the applications sandbox. Something is funky in the code I have. So I first get the DB path:
-(NSString *)getsynDbPath
{
NSString* dataBAse = [[NSBundle mainBundle] pathForResource:#"ddd"ofType:#"sqlite"];
return dataBAse;
}
Then I test the path:
NSString *testData;
testData = [self getsynDbPath];
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:testData];
if (success) {
NSLog(#"Oh no! There was a big problem!");
} else {
//Successfully opened
if(sqlite3_open([testData UTF8String], &db)==SQLITE_OK){
NSLog(#"Raise the roof!");
//Calling method to loop through columns
[self listOfCols];
}
}
I then go to a custom method where I loop through the columns inside the database:
-(NSArray *)listOfCols{
NSMutableArray *retval = [[[NSMutableArray alloc]init]autorelease];
NSString *query = #"SELECT KEY_ID FROM CON_DETAIL";
sqlite3_stmt *statement;
//Does not execute
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
int key_id = sqlite3_column_int(statement, 0);
NSLog(#"Key ID: %d", key_id);
char *nameChars = (char *) sqlite3_column_text(statement, 1);
NSLog(#"chars %s", nameChars);
char *cityChars = (char *) sqlite3_column_text(statement, 2);
NSLog(#"chars %s", cityChars);
}
}
NSLog(#"%s Why '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(db), sqlite3_errcode(db));
return retval;
}
So here's my question. After I successfully opened the database, why the heck am I getting a log error that says: no such table: CON_DETAIL ? Any help is appreciated.
I think you have to copy your db in your document directory and then try to fetch. Copy it with following functions.
-(void) dbconnect{
self.databaseName = #”yourdbname.sqlite”;
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
self.databasePath = [documentsDir stringByAppendingPathComponent:self.databaseName];
// Execute the “checkAndCreateDatabase” function
[self checkAndCreateDatabase];
}
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(success) {
return;
}
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
[fileManager release];
}
NOTE: If you are not getting db in your app’s document directory do the following.
Go to : Target -> “Build Phases” -> “copy bundle Resources” Then add that particular file here.
After that call your "listOfCols" method.
I am updating an entry in a database, the statement works and the code is updated in the database. Once the app has been closed and reopened though the database has not saved. It seems to create a temporary database and then not actually save to the database that the app is reading from.
Here is my code:
-(void)updateDatabase:(int)Level andPlayer:(int)questionID{
DataClass *obj=[DataClass getInstance];
//NSFileManager *filemgr = [NSFileManager defaultManager];
NSString* Database =[NSString stringWithFormat:#"levelProgress.db"];
NSString* databaseP = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:Database];
databasePath = [[NSString alloc]initWithString:databaseP];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &questionDB) == SQLITE_OK) {
NSString *querySQL = [NSString stringWithFormat:#"UPDATE levelProgress SET completed_questions=completed_questions+1 WHERE level=%d", obj.levelSelected];
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(questionDB, query_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE){
NSLog(#"update worked");
}else{
NSLog(#"did not work");
}
sqlite3_finalize(statement);
sqlite3_close(questionDB);
}
}
Any help with this would be greatly appreciated.
Copy database file databaseP from application bundle into user folder and then update that. You can't update any file in application bundle (they are always read only).
#define kDatabaseName (#"levelProgress.db")
- (void)checkAndCopyDatabaseIfNeeded
{
if (!self.databasePath)
{
// Database should be present in user sandbox at root.
self.databasePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], kDatabaseName, nil]];
}
// Check if the file already copied/exists.
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:self.databasePath];
if(!success)
{
// Copy the file from app bundle to user sandbox (Files in app bundle can not be edited).
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kDatabaseName];
#if DEBUG
BOOL isCopied =
#endif
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
NSAssert(isCopied, #"Problem copying database file to user document folder");
}
}
When the database is in the bundle it is read only. You will need to have your database in your documents directory when writing to it!
Have a look at the accepted answer here: Use and Access Existing SQLite Database on iOS
I am trying to execute a simple hard-coded insert statement for a SqLite database. The code works and I get a success message from my own NSLog, however, no records are added to the database. Can anyone help? THx! Viv
-(void)addFavorites{
const char *sqlInsert = "insert into rivers (stat_ID, stat_Name, state) values ('03186500','WILLIAMS RIVER','WA')";
sqlite3_stmt *statement;
sqlite3_prepare_v2(_database, sqlInsert, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE){
NSLog(#"RECORD ADDED!");
} else {
NSLog(#"RECORD NOT ADDED!");
}
sqlite3_finalize(statement);
}
Do you have code like this in your app delegate to copy the database out of the bundle to your NSDocuments directory? Be sure to copy the database to there, then point to there when you're running your sqlite3_open, not to the bundle. The NSDocument directory will be saved when the device is synced to iTunes or iCloud, so it's the place you want your database to be for maintaining data.
NSString *databaseName = #"MyDatabase.sqlite";
NSArray *systemPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [systemPaths objectAtIndex:0];
NSString *databaseFullPath = [libraryDirectory stringByAppendingFormat:#"%#%#",#"/",databaseName];
//copy the database to the file system if it hasn't been done yet.
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL exists = [fileManager fileExistsAtPath:databaseFullPath];
if(exists == NO)
{
NSString *dbPathInBundle = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:dbPathInBundle toPath:databaseFullPath error:nil];
}
This is the first time I'm trying to create and access a SQLite db in iOS and I followed a tutorial, but I can't make this work. These are the steps I've followed:
Created a database through the Firefox plugin ("testDatabase") and a
table ("testTable") with several columns
Saved the "testDatabase.sqlite" file in a directory
Dragged and dropped such file into my "Supporting Files" group in my
Xcode project
Added "libsqlite3.dylib" in Build Phases > Link Binary With
Libraries
Added "-lsqlite3" in Build Settings > Linking > Other Linker Flags >
Debug and Release
In a ViewController, called this method:
-(NSString *)copyDatabaseToDocuments {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"testDatabase.sqlite"];
if ( ![fileManager fileExistsAtPath:filePath] ) {
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"testDatabase.sqlite"];
[fileManager copyItemAtPath:bundlePath toPath:filePath error:nil];
}
return filePath;
}
Then, trying to write in the database:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"testDatabase.sqlite"];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into testTable (id) VALUES (?)";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiledStatement, 1, newObject.ID);
}
if(sqlite3_step(compiledStatement) == SQLITE_DONE) {
sqlite3_finalize(compiledStatement);
}
}
sqlite3_close(database);
I have read several posts regarding a similar error, but nothing of what I tried has worked for me... I also tried with NSString *filePath = [[NSBundle mainBundle] pathForResource:#"testDatabase" ofType:#"sqlite"]; but it is null, and also have underplayed and redeployed my app in the simulator several times...
Thanks in advance
I finally got this working by simply deleting the app folder generated in /Users/[user]/Library/Application Support/iPhone Simulator/5.1/Applications/ to be created again when running the simulator
I have an SQLite database, I can open it with SQLite browser, execute queries to it etc. But I can't get any data from it in my Xcode project.
NSString *databaseName = #"dbFile.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"db is ok"); // works just fine
const char *sqlStatement = "SELECT table.column FROM table";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"OK"); // nothing happens
}
sqlite3_close(database);
}
The very same query executed from SQLite browser for Mac works just fine.
sqlite3_open doesn't report all errors until you start accessing the data. For example just about any filename and path will pass without errors.
Are you sure the database is in the Documents folder? It's not there by default.
Perhaps it's in the main bundle?
Try
NSString *databaseName = [[NSBundle mainBundle] pathForResource:#"dbFile" ofType:#"db"];