can't create sqlite3 database in ios - iphone

Create Database Code
This code is correct. i used that code to create a database it's successful run and created a database but i test my application so i remove or delete my simulator app and again run my application then i see database is not created.
Please tell me what is the actual problem i face.
ClsUpdateNetworkViewController.h
#import <UIKit/UIKit.h>
#import "Person.h"
#import <sqlite3.h>
#interface ClsUpdateNetworkViewController : UIViewController{
UITextField *name;
UITextField *phone;
NSString *databasePath;
sqlite3 *contactDB;
int rowcount;
}
#property (nonatomic, strong) Person *person;
#property (nonatomic, strong) NSString *firstName;
#property (nonatomic, strong) NSString *lastName;
#property (nonatomic, strong) NSString *fullName;
#property (nonatomic, strong) NSString *phoneNumber;
#property (nonatomic, strong) NSString *workEmail;
#end
ClsUpdateNetworkViewController.m
#import "ClsUpdateNetworkViewController.h"
#import "ClsMainPageAppDelegate.h"
#import "ClsAddressBookViewController.h"
#interface ClsUpdateNetworkViewController ()
#end
#implementation ClsUpdateNetworkViewController
#synthesize person,firstName,lastName,fullName,phoneNumber,workEmail;
#synthesize name,phone;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self createDatabase];
}
-(void) createDatabase
{
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: #"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(contactDB);
}
else
{
NSLog(#"Failed to open/create database");
}
}
}
i test or debug my application
Code is not going inside this condition.
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
// inside code is not executed.
}

Call this Function at didFinishLaunchingWithOptions:
-(void)createdb
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:#"emp.sqlite"];
NSURL *dbURL = [NSURL fileURLWithPath:dbPath];
// copy a database from the bundle if not present
// on disk
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:dbPath])
{
NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:#"emp" withExtension:#"sqlite"];
NSError *error = nil;
if (!bundlePath || ![fm copyItemAtURL:bundlePath toURL:dbURL error:&error]) {
NSLog(#"error copying database from bundle: %#", error);
}
}
else
{
NSLog(#"Success in Copy file");
}
}

hi try this to create database only just add this code to your file
NSString *databaseName=#"Database.sqlite";
-(void)createDatabaseIfNeeded
{
// NSLog(#"Virtual database is created...");
NSFileManager *fileManager=[[NSFileManager defaultManager]autorelease];
NSError *error;
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path=[paths objectAtIndex:0];
NSString *finalPath=[path stringByAppendingPathComponent:databaseName];
// NSLog(#"Database Path is:--> %#",finalPath);
NSString *bundlePath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
success = [fileManager fileExistsAtPath:finalPath];
if(success)
{
if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
{
sqlite3_close(database);
}
return;
}
success=[fileManager copyItemAtPath:bundlePath toPath:finalPath error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with message '%#' .",[error localizedDescription]);
}
else//First Time Loaded Application....
{
if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
{
sqlite3_close(database);
}
}
}

How it worked for me is this
//-----------------------------------------------------------------------------------------------------//
#pragma mark - Shared Instance
//-----------------------------------------------------------------------------------------------------//
+ (SQLConnector *)database
{
static SQLConnector *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[SQLConnector alloc]init];
});
return _sharedClient;
}
//-----------------------------------------------------------------------------------------------------//
#pragma mark - Initialization Methods
//-----------------------------------------------------------------------------------------------------//
- (id)init {
if ((self = [super init]))
{
_databaseName = DB_NAME;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
NSLog(#"%#",_databasePath);
if (sqlite3_open([[self dbPath] UTF8String], &_database) != SQLITE_OK)
{
[[[UIAlertView alloc]initWithTitle:#"Missing"
message:#"Database file not found"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil]show];
}
}
return self;
}
- (NSString *)dbPath
{
[self checkAndCreateDatabase];
return _databasePath;
}
-(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:_databasePath error:nil];
}
//-----------------------------------------------------------------------------------------------------//
#pragma mark - Helper methods
//-----------------------------------------------------------------------------------------------------//
-(BOOL)dbOpenedSuccessfully
{
if(sqlite3_open([[self dbPath] UTF8String], &_database) == SQLITE_OK)
{
return YES;
}
else
{
[[[UIAlertView alloc]initWithTitle:#"Error"
message:#"Error on opening the DB"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil]show];
return NO;
}
}
//-----------------------------------------------------------------------------------------------------//
#pragma mark - Query
//-----------------------------------------------------------------------------------------------------//
- (void) executeQuery:(NSString *)strQuery
{
char *error = NULL;
if([self dbOpenedSuccessfully])
{
NSLog(#"%#",strQuery);
sqlite3_exec(_database, [strQuery UTF8String], NULL, NULL,&error);
if (error!=nil) {
NSLog(#"%s",error);
}
sqlite3_close(_database);
}
}

Related

Can't copy database file using copyItemAtPath with cocoa error 4

I want to copy the database file from bundle to user document.
My code is below:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *userPath = [documentsDir stringByAppendingPathComponent:#"db.sql"];
NSString *srcPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"db.sql"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Bundle database exists: %i",[fileManager fileExistsAtPath:srcPath]);
NSLog(#"User Document folder database exists: %i",[fileManager fileExistsAtPath:userPath]);
BOOL find = [fileManager fileExistsAtPath:userPath];
BOOL copySuccess = FALSE;
NSError *error;
if (!find) {
NSLog(#"don't have writable copy, need to create one");
copySuccess = [fileManager copyItemAtPath:srcPath toPath:userPath error:&error];
}
if (!copySuccess) {
NSLog(#"Failed with message: '%#'.",[error localizedDescription]);
}
and the result is always saying:
Bundle database exists: 1 User Document folder database exists: 0
don't have writable copy, need to create one Failed with message: 'The
operation couldn’t be completed. (Cocoa error 4.)'.
Please suggest, thanks.
Your code for determining your user's Documents Directory is incorrect.
Using your code, I put together a quick and dirty sample that works. For your application, you probably want to create some utils class that contains the static function 'applicationDocumentsDirectory' so that other classes in your project can call it, if needed.
Header File:
#import <UIKit/UIKit.h>
#interface TST_ViewController : UIViewController
+ (NSString *) applicationDocumentsDirectory;
#end
Implementation File:
#import "TST_ViewController.h"
#interface TST_ViewController ()
#end
#implementation TST_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *dbFilename = #"db.sql";
NSString *userPath = [[TST_ViewController applicationDocumentsDirectory] stringByAppendingPathComponent:dbFilename];
NSString *srcPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL foundInBundle = [fileManager fileExistsAtPath:srcPath];
BOOL foundInUserPath = [fileManager fileExistsAtPath:userPath];
BOOL copySuccess = FALSE;
NSError *error;
if(foundInBundle) {
if (!foundInUserPath) {
NSLog(#"Don't have a writable copy, so need to create one...");
copySuccess = [fileManager copyItemAtPath:srcPath toPath:userPath error:&error];
}
if (!copySuccess) {
NSLog(#"Failed with message: '%#'.",[error localizedDescription]);
}
} else {
// handle error in the event the file is not included in the bundle
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
#end

Can't permanently save audio with AVAudioRecorder

An app i'm making has several views, each view has a record, stop and play button. The idea is that the user can record to a different sound file for each view.
I can record and playback a sound on each view but when i navigate away from the view and then navigate back the sound is gone.
I'm sorry to include so much code below but it's something i need to get to the bottom of.
Delegate.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>
#import <AVFoundation/AVFoundation.h>
#interface humptyDumptyAppDelegate : UIResponder <UIApplicationDelegate>
{
NSArray *dirPaths;
NSString *docsDir;
NSString *soundFilePathPage1;
NSString *soundFilePathPage2;
NSString *soundFilePathPage3;
NSString *soundFilePathPage4;
NSString *soundFilePathPage5;
NSString *soundFilePathPage6;
}
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) AVAudioRecorder *audioRecorder;
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
//example getter and setter functions
- (NSArray*) getDirPaths;
- (void) setDirPaths:(NSArray*)myDirPath;
- (NSString*) getDocsDir;
- (NSString*) soundFilePathForPageNumber:(int)pageNumber;
#end
Delegate.m
#import "humptyDumptyAppDelegate.h"
#implementation humptyDumptyAppDelegate
#synthesize window = _window;
#synthesize audioPlayer;
#synthesize audioRecorder;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
soundFilePathPage1 = [docsDir
stringByAppendingPathComponent:#"audiopage1.caf"];
soundFilePathPage2 = [docsDir
stringByAppendingPathComponent:#"page2.caf"];
soundFilePathPage3 = [docsDir
stringByAppendingPathComponent:#"page3.caf"];
soundFilePathPage4 = [docsDir
stringByAppendingPathComponent:#"page4.caf"];
soundFilePathPage5 = [docsDir
stringByAppendingPathComponent:#"page5.caf"];
soundFilePathPage6 = [docsDir
stringByAppendingPathComponent:#"page6.caf"];
return YES;
}
//getter function
- (NSArray*) getDirPaths{
return dirPaths;
}
//setter function
- (void) setDirPaths:(NSArray*)myDirPath{
dirPaths = myDirPath;
}
// get docs directory
-(NSString*) getDocsDir{
return docsDir;
}
// get sound file for page, passing the page number as an argument
-(NSString*) soundFilePathForPageNumber:(int)pageNumber{
switch (pageNumber) {
case 1:
return soundFilePathPage1;
break;
case 2:
return soundFilePathPage2;
break;
case 3:
return soundFilePathPage3;
break;
case 4:
return soundFilePathPage4;
break;
case 5:
return soundFilePathPage5;
break;
case 6:
return soundFilePathPage6;
break;
}
return nil;
}
page1.m
//this is called in viewDidLoad
-(void) prepareForAudioRecording
{
btnPlay.enabled = NO;
btnStop.enabled = NO;
int page = 1;
NSString *audioFilePath = [appDelegate soundFilePathForPageNumber:page];
NSURL *soundFileURL = [NSURL fileURLWithPath:audioFilePath];
NSError *error;
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
appDelegate.audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[appDelegate.audioRecorder prepareToRecord];
}
}
- (IBAction)recordAudio:(id)sender {
if (!appDelegate.audioRecorder.recording)
{
btnPlay.enabled = NO;
btnStop.enabled = YES;
[appDelegate.audioRecorder record];
}
}
- (IBAction)stopAudio:(id)sender {
btnStop.enabled = NO;
btnPlay.enabled = YES;
btnRecord.enabled = YES;
if (appDelegate.audioRecorder.recording)
{
[appDelegate.audioRecorder stop];
[self audioRecorderDidFinishRecording:appDelegate.audioRecorder successfully:YES];
} else if (appDelegate.audioPlayer.playing) {
[appDelegate.audioPlayer stop];
}
}
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
if (flag == YES){
NSLog(#"finished recording");
[appDelegate.audioPlayer.data writeToFile:[appDelegate soundFilePathForPageNumber:1] atomically:YES];
}
}
Like i said, i'm sorry for the amount of code included, but i'm unsure where the problem is. I'm calling the writeToFile method in the audioRecorderDidFinishRecording: method. I don't know if this is correct but i have a feeling that this is not the root of the problem.
Please help!!
this code saves to an audio file
what about copping the file to the documents directory
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#" sound.caf"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (!success){
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sound.caf"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:writableDBPath error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"file size: %lld",fileSize);
if (!success) {
NSLog(#"Failed to create writable database file with message: %#", [error localizedDescription]);
}
}
It turns out the problem was that in one of my pages i had my prepareForAudioRecording in viewDidAppear which was automatically overwriting the saved audio. Moving it to viewDidLoad did the trick

sqlite database in iphone

How can I retain all the row from login table? I can retain only one row, why not others? Am I using wrong query? Please check my code:
#import "loginAppDelegate.h"
#import "global.h"
#import <sqlite3.h>
#import "logincontroller.h"
#implementation loginAppDelegate
#synthesize window;
#synthesize loginView;
//databaseName=#"login.sqlite";
-(void) chekAndCreateDatabase
{
BOOL success;
//sqlite3 *databaseName=#"login.sqlite";
NSFileManager *fileManager=[NSFileManager defaultManager];
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
success=[fileManager fileExistsAtPath:databasePath];
if(success)return;
NSString *databasePathFromApp=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:#"login.sqlite"];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void) Data
{
Gpass=#"";
Guname=#"";
sqlite3_stmt *detailStmt=nil;
//sqlite3 *databaseName;
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
[self chekAndCreateDatabase];
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String],&database)==SQLITE_OK) {
if (detailStmt==nil) {
const char *sql= "select *from Loginchk where uname='%?'and password='%?'";
//NSString *sql = [[NSString alloc] initWithFormat:#"SELECT * FROM Loginchk WHERE uname ='%#' and password ='%#' ",Uname.text,Password.text];
if (sqlite3_prepare_v2(database,sql,-1,&detailStmt,NULL)==SQLITE_OK) {
sqlite3_bind_text(detailStmt,1,[Gunameq UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(detailStmt,2,[Gpassq UTF8String],-1,SQLITE_TRANSIENT);
if (SQLITE_DONE!= sqlite3_step(detailStmt)) {
Guname=[NSString stringWithUTF8String:(char*)sqlite3_column_text(detailStmt,0)];
Gpass =[NSString stringWithUTF8String:(char*)sqlite3_column_text(detailStmt,1)];
NSLog(#"'%#'",Guname);
NSLog(#"'%#'",Gpass);
}
}
sqlite3_finalize(detailStmt);
}
}
sqlite3_close(database);
}
//Declare Class as Following to store user details UserDetails.h
#interface UserDetails : NSObject
{
NSString *strUserName;
NSString *strPassword;
}
#property (nonatomic,assign) NSString * strUserName;
#property (nonatomic,retain) NSString * strPassword;
//Declare Class as Following to store user details UserDetails.m
#implementation UserDetails
#synthesize strUserName,strPassword;
-(void)dealloc
{
[super dealloc];
[strUserName release];
[strPassword release];
}
//Declare Class as Following to store user details Your ApplicationDelegate.m file
-(NSMutableArray)getAllUserDetails
{
sqlite3_stmt *selectStmt = nil;
NSArray *documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =[documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:#"login.sqlite"];
[self chekAndCreateDatabase];
NSMutableArray *arrUsers = [[NSMutableArray alloc] init];
const char *sqlStatement = "your query";
if(sqlite3_prepare_v2(database, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(selectStmt) == SQLITE_ROW)
{
UserDetails *objUserDetail = [[UserDetails alloc] init];
objUserDetail.userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 1)];
objUserDetail.password = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 2)];
[arrUsers addObject:objUserDetail];
[objUserDetail release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(selectStmt);
selectStmt = nil;
}
call this function in button click event as
-(IBAction)btnLogin
{
BOOL isUserExists = NO;
NSMutableArray *arrAllUsers = [loginAppDelegate getAllUserDetails];
//Normal Checking Stuff
for(UserDetails *objUser in arrAllUsers)
{
if([txtUserTextBox.text isEqualToString:objUser.strUserName] && [txtPasswordTextBox.text isEqualToString:objUser.strPassword])
{
//True Login
isUserExists = YES;
break;
}
}
//Check your stuff if user exists or not what to do
if(isUserExists)
{
Heading to next screen;
}
else
{
Alertmessage
}
}

Getting error while trying to fetch and insert data into SQLite database

I am creating an application where I am using SQLite database to save data. But when I run my application I get the following errors:
#interface TDatabase : NSObject {
sqlite3 *database;
}
+(TDatabase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
#end
#import "TDatabase.h"
#import <sqlite3.h>
#implementation TDatabase
static TDatabase *SampleDataBase =nil;
+(TDatabase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[TDatabase alloc] init];
}
return SampleDataBase;
}
-(NSString *)GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return insertSql;
}
NSString *sql = #"select * from Location";
const location = [[TDatabase shareDataBase] getAllDataForQuery:sql forDatabase:#"journeydatabase.sqlite"];//1
NSString* insertSql = [NSString stringWithFormat:#"insert into Location values ('city','name','phone')"];//2
const insert =[[TDatabase shareDataBase] inseryQuery:insertSql forDatabase:#"journeydatabase.sqlite"];//3
in line no 1,2,3 I get the same error:
initializer element is not constant
What might be the problem?
#rani writing your own methods to deal with sqlite database is very painstaking. You should use fmdb wrapper class or use core data. I personally prefer fmdb. Initially I was doing the same way you were. I found about fmdb here. After using it I had to write very little code whenever I have to deal With sqlite db.

create sqlite db programmatically in iphone sdk

hai i a'm trying to create a sqlite database programmatically at the run time. can anybody say how to create it in iphone sdk.
Just call the sqlite3_open function it will create a database if no database exist on the path.
// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// your code here
}
post a comment if you need more code example on this
-(void)viewDidLoad
{
[super viewDidLoad];
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: #"contacts.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"if");
}
sqlite3_close(contactDB);
} else
{
NSLog(#"else");
}
}
[filemgr release];
}
-(IBAction)table
{
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: #"contacts.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
// if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"tables failed");
// status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
}
else
{
NSLog(#"tables failed");
//status.text = #"Failed to open/create database";
}
}
[filemgr release];
}
import in .m file #import sqlite3.h and add framework in ur project libsqlite3.0.dylib
firstly create NSObject class and named it Database.
in .h class
#interface database : NSObject
{
NSString *databasePath;
NSString *databaseName;
sqlite3 *myDatabase;
NSArray *documentPaths;
NSString *documentsDir;
}
//---initial methods-------
-(void)createDatabaseIfNeeded;
//-----------------path find method---------------------//
-(void)pathFind;
//-----------------write value----------------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue;
//-------------------fetch value from setting table------------//
-(NSMutableArray *)fetchValue;
//-------------------update value---------------------//
-(void)updateSetting:(NSArray *)arr;
.m class write
-(id)init
{
if((self=[super init]))
{
[self createDatabaseIfNeeded];
}
return self;
}
//-----------create database if needed method--------------//
-(void)createDatabaseIfNeeded
{
[self pathFind];
BOOL success;
NSFileManager *filemgr = [NSFileManager defaultManager];
success=[filemgr fileExistsAtPath:databasePath];
if (success)return;
NSLog(#"not success");
//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
[filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
//----------------path find-----------------//
-(void)pathFind
{
databaseName = #"accDataBase.DB";
// Get the path to the documents directory and append the databaseName
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
}
//------------------write value in setting----------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue
{
NSLog(#"%#",arrayvalue);
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
database *objectDatabase=[[database alloc]init];
NSString *stringvalue2=[objectDatabase countValue];
[objectDatabase release];
int intvalue1=[stringvalue2 intValue];
intvalue1=intvalue1+1;
NSLog(#"opened");
NSString *sql1;
sql1=[[NSString alloc] initWithFormat:#"insert into setting values('%i','%i','%i','%#','%i','%i','%#','%i','%i','%i','%i','%i','%i','%#');",intvalue1,
[[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
char *err1;
if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
{
NSLog(#"value inserted:");
}
[sql1 release];
sqlite3_close(myDatabase);
}
}
//------------fetch all value-------------//
-(NSMutableArray *)fetchValue
{
NSMutableArray *list=nil;
list=[[[NSMutableArray alloc]init] autorelease];
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *sql=[NSString stringWithFormat: #"select * from setting where primaryKey=1"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
{
if(sqlite3_step(statement)==SQLITE_ROW)
{
for(int i=0;i<=13;i++)
{
char *pass=(char*)sqlite3_column_text(statement,i);
NSString *msg=[[NSString alloc]initWithUTF8String:pass];
[list addObject:msg];
[msg release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return list;
}
//----------------update setting table method---------------//
-(void)updateSetting:(NSArray *)arr
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSLog(#"opened");
sqlite3_stmt *compiledStmt;
// NSLog(#"%#",arr);
NSString *sqlStmt=[NSString stringWithFormat:#"UPDATE setting SET ragular=%i,cycle=%i, flow='%#', hour=%i,minute=%i,formate='%#' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%#',formatemessage ='%#' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
// NSLog(#"%#",sqlStmt);
if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK)
{
NSLog(#"updateding......cycle");
}
sqlite3_step(compiledStmt);
sqlite3_close(myDatabase);
}
}