This is the code that I have used in Appdelegate.m to copy the database
- (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:#"LocalSongs.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
And this is used to get the DBPath
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"LocalSongs.sqlite"];
}
This is my playlist Insert method
-(NSString *)InsertPlaylist :(NSString *)PlaylistName
{
NSLog(#"passed");
NSString *status;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath=[[NSString alloc]initWithString:[documentsDir stringByAppendingPathComponent:#"LocalSongs.sqlite"]];
NSLog(#"Database Path %#",dbPath);
sqlite3_stmt *statement;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSLog(#"open");
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,getdate()) VALUES (\"%#\")",PlaylistName];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status=#"Playlist Created";
}
else
{
status=#"Error occured";
}
return status;
}
}
The problem I have is this prepare_v2 is always become notdone. It always execute the else part.
if (sqlite3_step(statement) == SQLITE_DONE)
What is the problem with this? Please help me
I think you have an error with your query: you are supposed to put a column name in the place you put getdate(), i.e. instead of
INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,getdate()) VALUES (\"%#\")
you should use something like
INSERT INTO LOCALPLAYLIST (PLAYLISTNAME,MYDATECOLUMN) VALUES (\"%#\",getdate())
After sqlite3_prepare_v2 the statement pointer is NULL?
Compare the return values of sqlite3_prepare_v2 and sqlite3_step with the ones in http://www.sqlite.org/c3ref/c_abort.html to get a better insight on what's going wrong
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;
}
I'm trying to add record to SQLite file but nothing happens. I get no error and in console I get that record is inserted in table #"----> RECORD INSERTED". Below you can see the code that I'm using. Please, can someone tell me how to fix this. Thanks for your time and help.
- (void)addRecordToSQLiteDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:#"ProductiivData.sqlite"];
success = [fileManager fileExistsAtPath:appDBPath];
if (success)
{
const char *databaseCharPath = [appDBPath UTF8String];
if (sqlite3_open(databaseCharPath, &(database)) == SQLITE_OK)
{
char *errorInsert;
const char *insertRecordInPROJECT = "insert into PROJECT values (139, 'TEST1888799')";
if (sqlite3_exec(database, insertRecordInPROJECT, NULL, NULL, &errorInsert))
{
NSLog(#"----> RECORD INSERTED");
}
else
{
NSLog(#"----> RECORD NOT INSERTED -- Error: %s", errorInsert);
}
char *errorSelectAll;
sqlite3_stmt *statement = NULL;
const char *allRecordsFromPROJECT = "select * from PROJECT";
if (sqlite3_prepare_v2(database, allRecordsFromPROJECT, 1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *projectName = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
}
}
else
{
NSLog(#"----> RECORDS NOT SELECTED -- Error: %s", errorSelectAll);
}
}
}
}
Separate insert and select logic, Try following code
Get Database path
+ (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"dbName.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
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]);
}
return dbPath;
}
Insert Data
+ (void)insertData
{
const char *dbpath = [[self getDBPath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *strSQL = [NSString stringWithFormat:#"INSERT INTO tableName………………."];
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);
}
else
{
NSLog(#"Error in opening database.");
}
}
Get data from table
+ (NSArray *)getDataList
{
NSMutableArray *arrProducts = [[NSMutableArray alloc] init];
const char *dbpath = [[self getDBPath] UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *strSQL = [NSString stringWithFormat:#"SELECT * FROM tableName"];
const char *selectQuery = [strSQL UTF8String];
sqlite3_stmt *select_stmt;
if(sqlite3_prepare_v2(database, selectQuery, -1, &select_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(select_stmt) == SQLITE_ROW)
{
NSInteger productID = sqlite3_column_int(select_stmt, 0);
NSString productNo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(select_stmt, 1)];
// Store above data into dictionary or object and then add this to array
[arrProducts addObject:dict];
}
}
}
else
{
NSLog(#"Error in opening database.");
}
return arrProducts;
}
I am trying to delete all the rows in database for that I wrote following codes ..
- (id)init {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"dataBase.sqlite3"];
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];
if (!databaseAlreadyExists){
NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:#"dataBase" ofType:#"sqlite3"];
[[NSFileManager defaultManager] copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
if (sqlite3_open([databasePath UTF8String], &_database) == SQLITE_OK){
}
return self;
}
-(void)deleteAll{
NSString *query = #"DELETE FROM user_info";
sqlite3_stmt *statement = nil;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
NSLog(#"Should delete..");
}
sqlite3_finalize(statement);
sqlite3_close(_database);
}
But when I rebuild the app data data appears. Whats wrong I am doing?
You never call sqlite3_step to actually execute the query.
Also, you close the database in the wrong place. Your close should be done opposite of the open.
First of all, get the database path after that open database
NSString *dbPath1=[SqliteManager getDataBasePath];
if (sqlite3_open([dbPath1 UTF8String], &database) == SQLITE_OK)
{
NSLog(#"opened the data base");
const char *sql = "delete from travels";
if(sqlite3_prepare_v2(database, sql, -1, &deletestmt, NULL) == SQLITE_OK)
if(SQLITE_DONE != sqlite3_step(deletestmt))
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(database));
else
isdeleted=YES;
}
sqlite3_reset(deletestmt);
sqlite3_close(database);
write in ur method inside.....
Getting Database Path....
+(NSString *)getDataBasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSLog(#"file Path is %#",documentsDir);
return [documentsDir stringByAppendingPathComponent:#"Give ur Sqlite Filename"];
}
Try a conditional if:
if(sqlite3_prepare_v2(database, sql, -1, &deletestmt, NULL) != SQLITE_OK)
I have built an sqlite3 database on the device. When I retrieved it to the pc and tried to open it through Xcode, I got result_code 14, cannot open database.
I need to open this database and read from it while it exist on the mac. I was able to access it and read from it when it was on the device.
Try this code
Create datbase... in Doc Directory..
-(void)createdatabase
{
NSString *databaseName = #"Card.sqlite"; // Name Of DataBase.
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = documentPaths[0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager] ;
success = [fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
Opening database and aceesss it's content..
- (void)getData
{
sqlite3 *database;
NSString *databasePath;
NSString *databaseName;
NSString *documentsDir;
NSArray *documentPaths;
databaseName = #"Card.sqlite";
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = documentPaths[0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement = "SELECT * FROM Master";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
[ID removeAllObjects];
[Name removeAllObjects];
[Image removeAllObjects];
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
[ID addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
[Name addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 1)]];
[Image addObject:[NSString stringWithFormat:#"%s",(char *) sqlite3_column_text(compiledStatement, 2)]];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
[tblView reloadData];
}
You can use SQLite Manager Firefox Plugin to read database, or use SQLiteManager
You can find your .sqlite file at : ~/Library/Application\ Support/iPhone\ Simulator/User/Applications/ ...
I am using sqlite database mathFActs in my project which i create through Sqlite Database Browser and add it to Xcode. following is my code from a view controller class
- (void)viewDidLoad
{ [super viewDidLoad];
[self copyDatabaseIfNeeded];
[self getInitialDataToDisplay:[self getDBPath]];
}
- (void) copyDatabaseIfNeeded {
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPth = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPth];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"mathFActs"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"mathFActs"];
}
-(void) getInitialDataToDisplay:(NSString *)databasePath{
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"open");
const char *sql = "select Question from math ";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"prepare");
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(selectstmt, 0)];
//address.text = addressField;
qstn.text=addressField;
sqlite3_finalize(selectstmt);
}}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
}
when i run the project it print open but not prepare means it's not executing query statement .. plz help me to solve my problem
Try this :-
-(void) getInitialDataToDisplay:(NSString *)databasePath
{
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
const char *sql = "select Question from math ";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"prepare");
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(selectstmt, 0)];
//address.text = addressField;
qstn.text=addressField;
}
sqlite3_reset(selectstmt);
}
else
{
NSLog(#"Error: failed to select details with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_finalize(selectstmt);
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
}
EDIT :-
-(void)copyDatabaseIfNeeded
{
#try
{
NSFileManager *fmgr=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
dbPath=[path stringByAppendingPathComponent:#"mathFActs.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:#"mathFActs.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