sqlite3_prepare error #26 - iphone

I have following code (modified code from this tutorial):
-(NSMutableArray *) getChampionDatabase
{
NSMutableArray *championsArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePath = [[NSBundle mainBundle]pathForResource: #"Champions Database" ofType:#"sqlite"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if (!success)
{
NSLog(#"cannot connect to Database! at filepath %#",databasePath);
}
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "SELECT CHAMPION_ID,CHAMPION_NAME,CHAMPION_IMG FROM CHAMPIONS";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(database, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
championList *ChampionList = [[championList alloc]init];
ChampionList.championId = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
ChampionList.championName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
ChampionList.championImage = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
[championsArray addObject:ChampionList];
}
}
else
{
NSLog(#"problem with database prepare");
}
}
else
{
NSLog(#"problem with database openning");
}
}
#catch (NSException *exception)
{
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally
{
return championsArray;
}
}
After running this code i always have output : "problem with database prepare"
Then i tried to check error number of sqlite3_prepare by following code:
int ret = sqlite3_prepare(database, sql, -1, &sqlStatement, NULL);
if (ret != SQLITE_OK) {
NSLog(#"Error calling sqlite3_prepare: %d", ret);
}
output: "Error calling sqlite3_prepare: 26"
error 26 - /*File opened that is not a database file */
File have sqlite 3 version
how is this possible? file extension is .sqlite and i can modify it in sqlite manager

Make sure you added your DB to the ressource bundle of your project and don't put any space in your name of your DB. For example use a name like champion_db.sqlite.

Related

Display multiple images from database

I created local database for storing multiple images. I stored this file to Mainbundle. When i fetch the data only one image will be displaying from database. But i need to display all images under scrollview.
code:
NSMutableArray *appArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"App4.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
const char *sql = "SELECT * FROM App4Tbl";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Myapp *Mylist = [[Myapp alloc]init];
Mylist.appId = sqlite3_column_int(sqlStatement, 0);
Mylist.app = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
Mylist.rating = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
const char *raw = sqlite3_column_blob(sqlStatement, 3);
int rawLen = sqlite3_column_bytes(sqlStatement, 3);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
Mylist.photo = [[UIImage alloc] initWithData:data];
[appArray addObject:Mylist];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return appArray;
}

Unable to update database

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}

Update statement not working properly [duplicate]

I'm having trouble updating my database. I believe it's due to it possibly being read only, however I am unsure. I created my database in my console, and the code below adds the database to the project folder rather than referencing it externally. Here is the code to transfer the file to the project folder
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
databaseName = #"databasenew.sql";
/* copy over to phone code */
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:#"databasenew.sql"];
if (![[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (error) {
NSLog(#"Could not copy json file: %#", error);
}
else{
NSLog(#"yea");
}
}
else{
NSLog(#"transfer complete");
}
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Here is the code where I try to update
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"Message"])
{
NSLog(soapResults);
NSString *convertString = soapResults;
check = [convertString intValue];
NSLog(#"user is");
NSLog(user);
if(check > 0){
databaseName = #"databasenew.sql";
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"databasenew" ofType:#"sql"];
databasePath = bundleSql;
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "UPDATE people set user = 'munch'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
NSLog(#"success");
NSLog(soapResults);
BOOL success = sqlite3_step(compiledStatement);
if (success != SQLITE_DONE) {
BOOL myBool=YES;
NSLog([NSString stringWithFormat:#"My Bool value : %d",success]);
}
}else{
NSLog(#"the fail ispreparing something");
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(compiledStatement);
}else{
NSLog(#"fail");
}
sqlite3_close(database);
NSString *string = [NSString stringWithFormat:#"%d", check];
NSLog(string);
NSLog(#"lolololol");
check = 0;
[self Bootup];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem!" message:#"Incorrect Username or Password"
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
// gotoContent = checkConfirm;
}
if( [elementName isEqualToString:#"ValidateUserResponse"])
{
if(!soapResults)
{
soapResults = [[NSMutableString alloc] init];
NSLog(soapResults);
NSLog(#"above is soap validate user");
}
recordResults = TRUE;
}
}
I've done my NDlog debugging and it says "success" as it should if the code for updating is successful, however the database itself does not update. What is the reason for this?
You are forgeting some code for update statement
//the binding part is missing in your code , you need to write after Prepare statement.
sqlite3_bind_text(compiledStatement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledStatement))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(compiledStatement);
Via iphonesdkarticles.com.
This will resolve your error.
-(BOOL) someUpdateFunction {
BOOL updatedSuccessfully = NO;
// Open the database.
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *updateQuery = [[NSString alloc] initWithFormat:#"UPDATE people SET user = 'terror' WHERE user = 'greg'"];
const char *query = [updateQuery UTF8String];
[updateQuery release];
sqlite3_stmt *statement;
int res = (sqlite3_prepare_v2( database, query, -1, &statement, NULL));
if(res == SQLITE_OK) {
int result = sqlite3_step(statement);
if(result == SQLITE_DONE) {
updatedSuccessfully = YES;
sqlite3_finalize(statement);
}else {
NSLog(#"Failed with error code: %d", result);
}
}else {
NSLog(#"Failed to prepare the update query with error code: %d", res);
}
}else {
NSLog(#"Failed to open the database");
}
sqlite3_close(database);
//NSLog(updatedSuccessfully);
//NSLog(#"The value of the bool is %#\n", updatedSuccessfully);
return updatedSuccessfully;
}
I was supplied this in the chat room. Thanks lads.
Remember to copy the DB over to the device else. You can find the DB path with this code:
- (NSString *) dataFilePath:(NSString *) dbName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
return dbPath;
}
-(BOOL)buildtheDB{
BOOL updatedSuccessfully = NO;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
NSString *sqlFile =[documentDirectory stringByAppendingPathComponent:kDatabaseFileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile] == NO) {
NSString *bundleSql = [[NSBundle mainBundle] pathForResource:#"database" ofType:#"sqlite"];
NSError *error = nil;
BOOL databaseCopied = [[NSFileManager defaultManager] copyItemAtPath:bundleSql toPath:sqlFile error:&error];
if (databaseCopied == NO) {
if (error) {
NSLog(#"Could not copy database file with error: %#", [error localizedDescription]);
}
}else {
NSLog(#"Database copied successfully");
}
}
else{
NSLog(#"Database already copied");
}
return updatedSuccessfully;
}

delete row from call_history.db on iOS4

I'm trying to delete rows from call_history.db. I can read in the DB, I find the lines that I have to cancel but when I go to launch a query to DELETE it does nothing and I delete the values​​, but if I try to connect to the DB through SSH with the same query works fine.
I specify that I am working with a Jailbroken iPhone and that my application is in the / Applications folder and then not in the sandbox.
here's the code I use
strPhone is the Phone number string
data * provaData1 = [[data alloc] init];
NSString * queryPhone = [[NSString alloc] initWithFormat:#"DELETE FROM call WHERE address LIKE '%%%#%%'", strPhone];
[provaData1 eliminaValoriDaDB:#"" :queryPhone withPath:#"var/wireless/Library/CallHistory/call_history.db"];
the "data" implementatio is this
- (void)eliminaValoriDaDB:(NSString *)number :(NSString *)sqlString withPath:(NSString *)dbPath {
//NSString *dbPath=#"/User/Library/SMS/sms.db";
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
if(delStmt == nil)
{
const char *sql = [sqlString UTF8String];
//const char *sql = [sqlDel UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &delStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating del statement. '%s'", sqlite3_errmsg(database));
}
if (![number isEqualToString:#""])
{
sqlite3_bind_int(delStmt, 1, [number intValue]);
}
if (SQLITE_DONE!= sqlite3_step(delStmt)) {
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(database));
}
sqlite3_reset(delStmt);
delStmt = nil;
}
else
NSLog(#"error db not open");
sqlite3_close(database);}
Plese help me....I do not know what to do
Thanks Andrea
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
NSArray *subPaths = [fileManager subpathsAtPath:#"/private/var/wireless/Library/CallHistory"];
for (NSString *aPath in subPaths) {
BOOL isDirectory;
[fileManager fileExistsAtPath:aPath isDirectory:&isDirectory];
if (isDirectory) {
NSDictionary *attrib = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedLong:775], NSFilePosixPermissions, nil ];
NSError *error = nil;
[fileManager setAttributes:attrib ofItemAtPath:aPath error:error];
if (error)
{
NSLog(#"error: %#", error);
}
}
}

Invalid SQLite table on iPhone?

I've been trying to access an SQLite3 database via my iphone, but I keep on getting "no such table: user_info" as an error.
So, here are the steps I've gone through:
Create the database via command line:
sqlite3 users.sqlite
create table user_info (name text, info text);
insert into user_info value('Name1', 'This is info for Name1');
select * from user_info;
[result]: Name1|This is info for Name1
select * from sqlite_master;
[result]: table|user_info|user_info|3|CREATE TABLE user_info (name text, info text)
Copy this into the resources folder in XCode, with the option to copy it to the appropriate directory.
Attempt to access it and get the error "no such table: user_info".
Okay, so how am I doing #3? Well, I've updated a bit, so now I try to create the table if it's non-existent. Here is my current code:
static NSString *dbname = #"users.sqlite";
-(NSString *) dbFilePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES
);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:dbname];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
fprintf(stderr, "Database is not writeable!\n");
}
return dbPath;
}
- (void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writeableDBPath = [self dbFilePath];
success = [fileManager fileExistsAtPath:writeableDBPath];
if (success) {
return;
}
NSString *defaultDBPath =
[[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:dbname];
success = [fileManager
copyItemAtPath:defaultDBPath
toPath:writeableDBPath
error:&error];
if (!success) {
fprintf(stderr, "Failed to create writable database file\n");
}
}
-(void) openDB {
if (sqlite3_open([[self dbFilePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
fprintf(stderr, "Database failed to open.\n");
}
}
-(void) createTableIfNeeded {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"CREATE TABLE IF NOT EXISTS user_info (name text info text);"
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
NSAssert1(0, "no user_info table!", nil);
fprintf(
stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db)
);
sqlite3_close(db);
return;
}
sqlite3_finalize(statement);
sqlite3_free(sql);
}
- (NSString *)getDatabaseEntry:(NSString *)i_name {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"SELECT 'info' FROM 'user_info' WHERE name='%q'",
[i_name cStringUsingEncoding:NSASCIIStringEncoding]
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
fprintf(
stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db)
);
sqlite3_close(db);
return result;
}
dbresult = sqlite3_step(statement);
if (SQLITE_ROW == dbresult) {
char *nfo = (char *)sqlite3_column_text(statement, 0);
result = [NSString stringWithUTF8String:nfo];
}
sqlite3_finalize(statement);
sqlite3_free(sql);
return result;
}
// viewDidAppear
- (void)viewDidAppear:(BOOL)animated {
[self createEditableCopyOfDatabaseIfNeeded];
[self openDB];
[self createTableIfNeeded];
}
// Later, when I have a valid user:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
...
NSString *nfo = [self getDatabaseEntry:name.text];
...
}
I've been against this wall for a couple of days now, so any help is greatly appreciated.
Well, I fixed it, but I'm not certain on how.
I created a blank project and followed the tutorial here:
http://www.raywenderlich.com/913/sqlite-101-for-iphone-developers-making-our-app
And made sure that worked. (It did.)
I then used the bit from here:
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml
To copy the database into a location where it's writeable. I had very similar code before.
So now it works.
I built a new table specifically with the "sqlite3" extensions. I don't know if this actually makes a difference or not.
I also used:
[[NSBundle mainBundle] pathForResource:#"users" ofType:#"sqlite3"];
As opposed to:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
Again, no idea if this matters or not.
Hopefully this helps someone else out!
//----------------------------------------------------------------------------
-(NSString *) dbFilePath {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"users.sqlite3"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
fprintf(stderr, "Database is not writeable! Attempting to create writeable database.\n");
NSString *bundle_path = [[NSBundle mainBundle] pathForResource:#"users" ofType:#"sqlite3"];
success = [fileManager copyItemAtPath:bundle_path toPath:dbPath error: &error];
if (!success) {
fprintf(stderr, "Failed to create writeable database file\n");
}
}
return dbPath;
}
//----------------------------------------------------------------------------
-(void) openDB {
if (sqlite3_open([[self dbFilePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
fprintf(stderr, "Database failed to open.\n");
}
}
//----------------------------------------------------------------------------
- (NSString *)getDatabaseEntry:(NSString *)i_name {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"SELECT info FROM user_info WHERE name='%q'",
[i_name cStringUsingEncoding:NSASCIIStringEncoding]
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
fprintf(stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
sqlite3_free(sql);
return result;
}
dbresult = sqlite3_step(statement);
if (SQLITE_ROW == dbresult) {
char *nfo = (char *)sqlite3_column_text(statement, 0);
result = [NSString stringWithUTF8String:nfo];
}
sqlite3_finalize(statement);
sqlite3_free(sql);
return result;
}