all
i want to create the header file for database like this.
it contains following six files.
Database.h
#import <Foundation/Foundation.h> #import "sqlite3.h" @interface Database : NSObject { sqlite3 *mydb; } -(void) openDB; -(NSString *) filePath; -(BOOL) createTable; +(Database*)sharedInstance; @end
Database.m
#import “Database.h”
@implementation Database
static Database* dbase = nil;
+(Database*)sharedInstance
{
if (dbase == nil)
{
dbase = [[Database alloc] init];
}
return dbase;
}
-(NSString *) filePath{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSLog(@"DBPATH:%@",documentsDir);
return [documentsDir stringByAppendingPathComponent:@"userdb.sqlite"];
}
-(void) openDB {
if (sqlite3_open([[self filePath]UTF8String],&mydb) != SQLITE_OK) {
sqlite3_close(mydb);
NSAssert(0,@"Database failed to Open ...");
}
BOOL result = [self createTable];
NSLog(@"Table Avi gayu 6...!!! %u",result);
}
- (BOOL) createTable
{
sqlite3_stmt *createStmt;
createStmt = nil;
NSString *tableName = @"user_table";
if ( createStmt == nil )
{
NSString *query = [NSString stringWithFormat:@"create table if not exists %@ \
(userid INTEGER PRIMARY KEY, \
name TEXT NOT NULL)",tableName];
if (sqlite3_prepare_v2(mydb, [query UTF8String], -1, &createStmt, NULL)!= SQLITE_OK )
{
return NO;
}
sqlite3_exec(mydb, [query UTF8String], NULL, NULL, NULL);
return YES;
}
return YES;
}
@end
UIDBDemoAppDelegate.h
#import <UIKit/UIKit.h> #import "Database.h" @class UIDBDemoViewController; @interface UIDBDemoAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UIDBDemoViewController *viewController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UIDBDemoViewController *viewController; @end
UIDBDemoAppDelegate.m
#import "UIDBDemoAppDelegate.h" #import "UIDBDemoViewController.h" @implementation UIDBDemoAppDelegate @synthesize window; @synthesize viewController; #pragma mark - #pragma mark Application lifecycle - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[Database sharedInstance] openDB]; [self.window addSubview:viewController.view]; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { } - (void)applicationDidEnterBackground:(UIApplication *)application { } - (void)applicationWillEnterForeground:(UIApplication *)application { } - (void)applicationDidBecomeActive:(UIApplication *)application { } - (void)applicationWillTerminate:(UIApplication *)application { } #pragma mark - #pragma mark Memory management - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { } - (void)dealloc { [viewController release]; [window release]; [super dealloc]; } @end
UIDBDemoViewController.h
#import <UIKit/UIKit.h> #import "UIDBDemoAppDelegate.h" @interface UIDBDemoViewController : UIViewController <UITableViewDataSource> { UIView *addView; UILabel *uid,*unm,*cellLbl1,*cellLbl2; UITextField *txtuid,*txtunm; UIButton *btnadd,*btnshow; UITableView *mytabView; NSMutableArray *uidarray,*unmarray; } @property (retain, nonatomic) UIView *addView; @property (retain, nonatomic) UILabel *uid,*unm; @property (retain, nonatomic) UITextField *txtuid,*txtunm; @property (retain, nonatomic) UIButton *btnadd,*btnshow; -(void) addClicked; -(void) showClicked; -(void) readData; -(void) rmkeyboard; @end
UIDBDemoViewController.m
#import "UIDBDemoViewController.h"
@implementation UIDBDemoViewController
@synthesize addView, uid,unm,txtuid,txtunm,btnadd,btnshow;
- (void)loadView
{
//Add myView
CGRect rect = CGRectMake(0, 0, 320, 480);
addView = [[UIView alloc] initWithFrame:rect];
addView.backgroundColor=[UIColor blackColor];
//Adding two Name and Password Label into myView
uid=[[UILabel alloc] initWithFrame:CGRectMake(20, 100, 100, 35)];
uid.text=@"User ID:";
uid.textAlignment=UITextAlignmentRight;
uid.textColor=[UIColor whiteColor];
uid.backgroundColor=[UIColor blackColor];
[addView addSubview:uid];
unm=[[UILabel alloc] initWithFrame:CGRectMake(20, 140, 100, 35)];
unm.text=@"User Name:";
unm.textAlignment=UITextAlignmentRight;
unm.textColor=[UIColor whiteColor];
unm.backgroundColor=[UIColor blackColor];
[addView addSubview:unm];
//Adding Two Name and Password TextField into myView
txtuid=[[UITextField alloc] initWithFrame:CGRectMake(130, 100, 150, 30)];
txtuid.placeholder=@"Enter User ID";
txtuid.borderStyle=UITextBorderStyleRoundedRect;
[txtuid addTarget:self action:@selector(rmkeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
[addView addSubview:txtuid];
txtunm=[[UITextField alloc] initWithFrame:CGRectMake(130, 140, 150, 30)];
txtunm.placeholder=@"Enter User Name";
txtunm.borderStyle=UITextBorderStyleRoundedRect;
[txtunm addTarget:self action:@selector(rmkeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
[addView addSubview:txtunm];
//Adding Two Button Login and Cancel into myView
btnadd=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnadd.frame=CGRectMake(50, 200, 100, 35);
[btnadd setTitle:@"ADD" forState:UIControlStateNormal];
[btnadd addTarget:self action:@selector(addClicked) forControlEvents:UIControlEventTouchUpInside];
[addView addSubview:btnadd];
btnshow=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btnshow.frame=CGRectMake(180, 200, 100, 35);
[btnshow setTitle:@"SHOW" forState:UIControlStateNormal];
[btnshow addTarget:self action:@selector(showClicked) forControlEvents:UIControlEventTouchUpInside];
[addView addSubview:btnshow];
self.view=addView;
}
-(void) rmkeyboard
{
[txtuid resignFirstResponder];
[txtunm resignFirstResponder];
}
-(void)readData
{
NSString *query = [NSString stringWithString:@"select * from user_table"];
sqlite3_stmt *selectStatement;
uidarray = [[NSMutableArray alloc] init];
unmarray = [[NSMutableArray alloc] init];
int userid;
NSString *username;
int i=0;
if (sqlite3_prepare_v2([Database sharedInstance], [query UTF8String], -1, &selectStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectStatement)== SQLITE_ROW)
{
userid = sqlite3_column_int(selectStatement, 0);
username = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, 1)];
[uidarray addObject:[NSString stringWithFormat:@"%d",userid]];
[unmarray addObject:username];
NSLog(@"id=%@",[uidarray objectAtIndex:i]);
NSLog(@"unm=%@",[unmarray objectAtIndex:i]);
i++;
}
sqlite3_finalize(selectStatement);
}
}
-(void) showClicked
{
printf("Hello... showClicked");
//Tableview
mytabView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 300) style:UITableViewStylePlain] autorelease];
[mytabView setDataSource:self];
[addView addSubview:mytabView];
[self readData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [uidarray count];
}
// Return a cell for the specified index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"any-cell"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"any-cell"] autorelease];
}
CGFloat height=[tableView rowHeight];
cellLbl1=[[UILabel alloc]initWithFrame:CGRectMake(20, 0,60, height)];
cellLbl2=[[UILabel alloc]initWithFrame:CGRectMake(150, 0,100, height)];
cellLbl1.text=[uidarray objectAtIndex:[indexPath row]];
cellLbl2.text=[unmarray objectAtIndex:[indexPath row]];
[cell addSubview:cellLbl1];
[cell addSubview:cellLbl2];
return cell;
}
-(void) addClicked
{
NSLog(@"Add Dabavyu...");
sqlite3_stmt *insertStmt;
NSString *suid = txtuid.text;
NSInteger iuid = [suid intValue];
NSString *sunm = [NSString stringWithFormat:@"%@",txtunm.text];
NSString *insertQuery = [NSString stringWithFormat:@"insert into user_table values (%d,'%@');",iuid,sunm];
NSLog(@"int Query= %@",insertQuery);
if (sqlite3_prepare_v2([Database sharedInstance], [insertQuery UTF8String], -1, &insertStmt, NULL) != SQLITE_OK)
{
NSLog(@"Inserting Failed....!!!!");
return;
}
sqlite3_exec([Database sharedInstance], [insertQuery UTF8String], NULL, NULL, NULL);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload { }
- (void)dealloc {
[super dealloc];
}
@end
i want to use this same object into Controller file to
insert data into database table user_table.
i have given a full source code of application.
i m getting warning passing argument 1 of ‘sqlite3_prepare_v2’ from incompatible pointer type & because of this i could not open connection to db from cnrtl File pls guide me how to solve it.
pls help me.
i m beginner in iphone programming.
Create a singleton object like following:
In header file:
In implementation file:
When ever you want to call database just get the object of database using the method
[Database sharedInstance]