TO Handle small application "Sqlite is Best"
CCDDatabase.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "StudentInfo.h"
@interface
CCDDatabase : NSObject {
sqlite3 *db;
}
@property(nonatomic,assign)sqlite3 *db;
+(NSString
*) DocumentsDirectory;
+(NSString
*) PathForResource:(NSString *)fileName;
-(id)initWithDB;
-(void)makeWritableDatabase;
-(void)makeWritableXML;
-(NSString
*)dbPath;
-(void)insertStudent:(StudentInfo *)studdata;
-(void)insertstudentdata:(StudentInfo *)studdata;
-(void)updateStudentData:(StudentInfo *)studdata;
-(void)deletestudentdata:(NSString *)studdata;
-(NSMutableArray
*)selectStudent;
@end
(datatype of photo is "image" in sqlite)
I have store photo in binary form in database.
CCDDatabase .m
#import "CCDDatabase.h"
#import <sqlite3.h>
NSString
*DATABASE_FILENAME=@"Demo.sqlite";
NSString
*XML_FILENAME=@"DOC00001.XML";
@implementation
CCDDatabase
@synthesize
db;
//for db we require
PathForResource,DocumentsDirectory,initWithDB,dealloc,makeWritableDatabase
methods
+(NSString
*) PathForResource:(NSString *)fileName{
NSString *leftpart=[fileName stringByDeletingPathExtension];
NSString *extension=[fileName pathExtension];
return [[NSBundle
mainBundle] pathForResource:leftpart
ofType:extension];
}
+(NSString
*) DocumentsDirectory{
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,
YES);
//NSLog(@"%@",paths);
return [paths objectAtIndex:0];
}
-(id)initWithDB
{
self=[super init];
if (self)
{
int status= sqlite3_open([[self dbPath] UTF8String], &db);
if (status!= SQLITE_OK)
{
NSLog(@"ERROR
opening database");
exit(1);
}
}
return self;
}
-(void)dealloc
{
sqlite3_close(db);
[super dealloc];
}
-(NSString
*)dbPath{
return [[CCDDatabase
DocumentsDirectory] stringByAppendingPathComponent:DATABASE_FILENAME];
}
-(void)makeWritableDatabase{
NSString *targetPath=[[CCDDatabase
DocumentsDirectory] stringByAppendingPathComponent:DATABASE_FILENAME];
//NSLog(@"%@",targetPath);
NSFileManager *filemgr=[NSFileManager
defaultManager];
if ([filemgr fileExistsAtPath:targetPath])
{
//NSLog(@"file exists");
return;
}
NSString *sourcepath=[CCDDatabase
PathForResource:DATABASE_FILENAME];
[filemgr
copyItemAtPath:sourcepath toPath:targetPath error:nil];
//NSLog(@"copied");
return;
}
-(void)makeWritableXML
{
NSString *targetPath_xml=[[CCDDatabase DocumentsDirectory]
stringByAppendingPathComponent:XML_FILENAME];
NSFileManager *filemgr=[NSFileManager
defaultManager];
if ([filemgr fileExistsAtPath:targetPath_xml])
{
return;
}
NSString *sourcepath_xml=[CCDDatabase
PathForResource:XML_FILENAME];
[filemgr
copyItemAtPath:sourcepath_xml toPath:targetPath_xml error:nil];
return;
}
-(void)insertStudent:(StudentInfo *)studdata
{
NSData *imgData=UIImagePNGRepresentation([studdata
imageview]);
NSString *name=[studdata name];
const char*
sqlitequery="insert into
student_master(name,image) values(?,?)";
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(db,
sqlitequery, -1, &stmt, NULL)==SQLITE_OK)
{
sqlite3_bind_text(stmt, 1,[name
UTF8String] , -1,
SQLITE_TRANSIENT);
sqlite3_bind_blob(stmt, 2,
[imgData bytes], [imgData length], SQLITE_TRANSIENT);
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
}
-(void)insertstudentdata:(StudentInfo *)studdata
{
sqlite3_stmt *stmt;
NSData *imgData=UIImagePNGRepresentation([studdata
imageview]);
NSString *str=[@""
stringByAppendingFormat:@"insert or replace into student_master(name,image)
values('%@','%@')",[studdata name],[imgData
bytes]];
//const char *sql=[str UTF8String];
const char
*sql=[str UTF8String];
int status;
status=sqlite3_prepare_v2(db, sql, -1,
&stmt, NULL); //status=;
if(SQLITE_DONE
!=sqlite3_step(stmt))
{
NSAssert1(0,
@"error on updation '%s'", sqlite3_errmsg(db));
exit(1);
}
sqlite3_bind_text(stmt, 1,
[[studdata name] UTF8String],
-1, SQLITE_TRANSIENT);
int returnValue=-1;
if(studdata.imageview!=nil)
returnValue=sqlite3_bind_blob(stmt, 2, [imgData bytes],
[imgData length], NULL);
else
returnValue=sqlite3_bind_blob(stmt, 2, nil, -1, NULL);
sqlite3_finalize(stmt);
}
-(void)updateStudentData:(StudentInfo *)studdata
{sqlite3_stmt
*stmt;
NSData *imgData=UIImagePNGRepresentation([studdata
imageview]);
// NSString
*str=[@"" stringByAppendingFormat:@"update student_master set
name=? where id=?",[studdata name],[studdata studid]];
const char*
sql="update student_master set name=? ,
image=? where id=?";
// const char *sql=[str UTF8String];
//int status;
NSString *name=[studdata name];
NSInteger setid=[[studdata studid]intValue ];
NSLog(@"%@",name);
if(sqlite3_prepare_v2(db, sql, -1,
&stmt, NULL)==SQLITE_OK)
{
sqlite3_bind_text(stmt, 1,[name UTF8String],
-1, SQLITE_TRANSIENT);
sqlite3_bind_blob(stmt, 2,[imgData bytes],
[imgData length], SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 3, setid);
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
}
-(void)deletestudentdata:(NSString *)studdata
{
sqlite3_stmt *stmt;
NSString *str=[@""
stringByAppendingFormat:@"delete from student_master where id=%@",studdata];
const char
*sql=[str UTF8String];
int status;
status=sqlite3_prepare_v2(db, sql, -1,
&stmt, NULL);
if(SQLITE_DONE
!=sqlite3_step(stmt))
{
NSAssert1(0,
@"error on deleting '%s'", sqlite3_errmsg(db));
exit(1);
}
sqlite3_finalize(stmt);
}
-(NSMutableArray
*)selectStudent
{
NSMutableArray *resArray=[[NSMutableArray alloc] init];
sqlite3_stmt *stmt;
NSString *str=@"select
* from student_master";
//const char *sql= [str UTF8String];
const char
*sql= [str cStringUsingEncoding:NSUTF8StringEncoding];
int status;
status=
sqlite3_prepare_v2(db,sql,
-1, &stmt, NULL);
if(status != SQLITE_OK)
{
NSLog(@"error
preparing statement 2 '%s'",sqlite3_errmsg(db));
exit(1);
}
while ((status=sqlite3_step(stmt))
== SQLITE_ROW)
{
int length=sqlite3_column_bytes(stmt,
2);
StudentInfo *stude=[[StudentInfo alloc]init ];
[stude setStudid:[NSString stringWithFormat:@"%s",sqlite3_column_text(stmt,
0)]];
[stude setName:[NSString stringWithFormat:@"%s",sqlite3_column_text(stmt,
1)]];
//[stude setImageview:[NSData
dataWithBytes:sqlite3_column_blob(stmt, 2) length:length]];
[stude
setDta:[NSData
dataWithBytes:sqlite3_column_blob(stmt,
2) length:length]];
[resArray addObject:stude];
[stude
release];
}
sqlite3_finalize(stmt);
return resArray;
}
@end
I have created Class for storing and fetching data
StudentInfo.h
#import <Foundation/Foundation.h>
@interface
StudentInfo : NSObject
@property(retain,nonatomic)
NSString *name;
@property(retain,nonatomic)NSString *studid;
@property(retain,nonatomic)UIImage *imageview;
@property(retain,nonatomic)NSData *dta;
@end
StudentInfo.m
#import "StudentInfo.h"
@implementation
StudentInfo
@synthesize
name;
@synthesize
studid;
@synthesize
imageview;
@synthesize
dta;
@end
Now inserting data
Getting image from picture gallery
Getting image from picture gallery
- (IBAction)btnUploadImage:(id)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
[self presentModalViewController:image1 animated:YES];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
self.imageview1=image;
[self.showImage setImage:image];
[picker dismissModalViewControllerAnimated:YES];
}
//// inserting data
StudentInfo *stud1=[[StudentInfo
alloc]init
];
stud1.name=txtname.text;
[stud1 setImageview:self.imageview1];
NSLog(@"%@",stud1.name);
CCDDatabase *dbase=[[CCDDatabase
alloc]initWithDB
];
if([studentID isEqualToString:@""])//for insertion
{
[dbase insertStudent:stud1];
// [dbase insertStudent:txtname.text];
}
else // for updation
{
stud1.studid=[NSString stringWithFormat:@"%@",studentID];
// NSLog(@"%@
%@",studinfo.studid,studinfo.name);
[dbase updateStudentData:stud1];
}
[self.navigationController
popViewControllerAnimated:YES];
Showing data in UITableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arydata
count]; // arydata is a object of NSArray which is declare
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(UITableViewCell
*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static
NSString *cell=@"cell";
UITableViewCell *cellview=[tableView dequeueReusableCellWithIdentifier:cell];
if(cellview==nil)
{
cellview=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell] autorelease];
}
StudentInfo *stud=[self.arydata objectAtIndex:[indexPath
row]];
cellview.ImageView.image=[UIImage imageWithData:stud.dta];// show image
cellview.textLabel.text=stud.name; // show name
cellview.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cellview;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
StudentInfo *std=[self.arydata objectAtIndex:[indexPath
row]];
StudentEntry *stude=[[StudentEntry
alloc]init
];
stude.studentID=std.studid;
stude.stud=[arydata
objectAtIndex:indexPath.row];
[self.navigationController
pushViewController:stude animated:YES];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
StudentInfo *std=[arydata
objectAtIndex:[indexPath row]];
CCDDatabase *dbase=[[CCDDatabase
alloc]initWithDB
];
NSLog(@"%@",std.studid);
NSString *studid=[NSString stringWithFormat:@"%@",std.studid];
[dbase deletestudentdata:studid]; // for deleting the record
[arydata removeObjectAtIndex:[indexPath
row]];
[self.tableView deleteRowsAtIndexPaths:[NSArray
arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
/// call method to fetch all record from database
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
CCDDatabase *dbase=[[CCDDatabase
alloc]initWithDB
];
// arydata=[dbase selectStudent];
arydata=[dbase selectStudent];
[tableView setDelegate:self];
[tableView setDataSource:self];
[tableView reloadData];
}