Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am developing an application in iphone and am new to iphone.
Kindly let me know the code for open/close/update/delete database record in iphone using sqlite?
Regards,
Vijaya
import
In .h file
- (void)createEditableCopyOfDatabaseIfNeeded;
+ (sqlite3 *) getNewDBConnection;
Add the following code in appdelegate.m in didFinishLaunching method:
[self createEditableCopyOfDatabaseIfNeeded];
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Scores.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Scores.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message ‘%#’.", [error localizedDescription]);
}
}
+ (sqlite3 *) getNewDBConnection {
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Scores.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
NSLog(#"Database Successfully Opened ");
} else {
NSLog(#"Error in opening database ");
}
return newDBconnection;
}
In your view controller call the method of insertion etc. here i called a method which brings me the data from table
sqlite3* db =[iMemory_SharpenerAppDelegate getNewDBConnection];
sqlite3_stmt *statement = nil;
const char *sql = "select * from HighScore";
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK) {
NSAssert1(0,#"error prepearing statement",sqlite3_errmsg(db));
} else {
while (sqlite3_step(statement)==SQLITE_ROW) {
//dt= [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
dt = [NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement, 0)];
//dt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSLog(#"%#score==",dt);
[nmber addObject:dt];
}
}
sqlite3_finalize(statement);
sqlite3_close(db);
Read the sqlite documentation on their website. They have API references and tutorials. All you need to get going in XCode is to add the libsqlite3.dylib to the referenced frameworks.
Here is a sample code to connect SQLite from iOS:(insertion of data)
Source:http://sickprogrammersarea.blogspot.in/2014/03/sqlite-in-ios-using-objective-c.html
#import "sqlLiteDemoViewController.h"
#interface sqlLiteDemoViewController (){
UILabel *lblName;
UILabel *lblRoll;
UILabel *lblAge;
UITextField *txtName;
UITextField *txtroll;
UISlider *sldAge;
}
#end
#implementation sqlLiteDemoViewController
- (void)viewDidLoad
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent:#"student.db"]];
NSLog(#"%#",_databasePath);
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 STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ROLL TEXT, AGE TEXT)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(_contactDB);
NSLog(#"Connection Successful");
} else {
NSLog(#"Failed to open/create database");
}
}
UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapped)];
[self.view addGestureRecognizer:tapScroll];
[super viewDidLoad];
lblName = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 50)];
lblName.backgroundColor = [UIColor clearColor];
lblName.textColor=[UIColor blackColor];
lblName.text = #"Name";
[self.view addSubview:lblName];
lblRoll = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 100, 50)];
lblRoll.backgroundColor = [UIColor clearColor];
lblRoll.textColor=[UIColor blackColor];
lblRoll.text = #"Roll no";
[self.view addSubview:lblRoll];
lblAge = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, 100, 50)];
lblAge.backgroundColor = [UIColor clearColor];
lblAge.textColor=[UIColor blackColor];
lblAge.text = #"Age";
[self.view addSubview:lblAge];
txtName = [[UITextField alloc] initWithFrame:CGRectMake(80, 40, 200, 40)];
txtName.borderStyle = UITextBorderStyleRoundedRect;
txtName.font = [UIFont systemFontOfSize:15];
txtName.placeholder = #"Specify Name";
txtName.autocorrectionType = UITextAutocorrectionTypeNo;
txtName.keyboardType = UIKeyboardTypeDefault;
txtName.returnKeyType = UIReturnKeyDone;
txtName.clearButtonMode = UITextFieldViewModeWhileEditing;
txtName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtName.delegate = self;
[self.view addSubview:txtName];
txtroll = [[UITextField alloc] initWithFrame:CGRectMake(80, 90, 200, 40)];
txtroll.borderStyle = UITextBorderStyleRoundedRect;
txtroll.font = [UIFont systemFontOfSize:15];
txtroll.placeholder = #"Specify Roll";
txtroll.autocorrectionType = UITextAutocorrectionTypeNo;
txtroll.keyboardType = UIKeyboardTypeNumberPad;
txtroll.returnKeyType = UIReturnKeyDone;
txtroll.clearButtonMode = UITextFieldViewModeWhileEditing;
txtroll.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
txtroll.delegate = self;
[self.view addSubview:txtroll];
CGRect frame = CGRectMake(80.0, 140.0, 200.0, 40.0);
sldAge= [[UISlider alloc] initWithFrame:frame];
[sldAge setBackgroundColor:[UIColor clearColor]];
sldAge.minimumValue = 0;
sldAge.maximumValue = 30;
sldAge.continuous = YES;
sldAge.value = 15.0;
[self.view addSubview:sldAge];
UIButton *subButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
subButton.frame = CGRectMake(80.0, 200.0, 80.0, 30.0);
[subButton setTitle:#"Store" forState:UIControlStateNormal];
subButton.backgroundColor = [UIColor clearColor];
[subButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[subButton addTarget:self action:#selector(store:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:subButton];
UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame = CGRectMake(200.0, 200.0, 80.0, 30.0);
[srchButton setTitle:#"Search" forState:UIControlStateNormal];
srchButton.backgroundColor = [UIColor clearColor];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[srchButton addTarget:self action:#selector(find:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:srchButton];
}
- (void)tapped {
[self.view endEditing:YES];
}
-(void)store:(id)sender{
#try{
NSLog(#"store called");
sqlite3_stmt *statement;
const char *dbpath = (const char *)[_databasePath UTF8String];
NSString *age=[NSString stringWithFormat:#"%g", sldAge.value];
NSLog(#"Age is %#",age);
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO STUDENT (name, roll , age) VALUES (\"%#\", \"%#\", \"%#\")",
txtName.text, txtroll.text, age];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Insertion Successful");
} else {
NSLog(#"Insertion Failure");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}#catch (NSException *e) {
NSLog(#"Exception : %s",sqlite3_errmsg(_contactDB));
}
}
- (void) find:(id)sender
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT roll, age FROM STUDENT WHERE name=\"%#\"",txtName.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *roll = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
txtroll.text = roll;
NSString *age = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
sldAge.value = [age floatValue];
NSLog(#"Match found");
} else {
NSLog(#"Match found");
txtroll.text = #"";
sldAge.value = 0.0;
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
}
ViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface ViewController
{
IBOutlet UITextField *no;
UITextField *name,*address;
IBOutlet UIButton *save,*update,*del,*clear,*Find,*showdata;
sqlite3 *contactDB;
IBOutlet UILabel *status;
}
#property (strong, nonatomic) IBOutlet UITextField *no;
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *address;
#property (retain, nonatomic) IBOutlet UILabel *status;
- (IBAction)SaveData:(id)sender;
- (IBAction)FindData:(id)sender;
- (IBAction)UpdateData:(id)sender;
- (IBAction)DeleteData:(id)sender;
- (IBAction)ClearData:(id)sender;
- (IBAction)ShowData:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import "ShowRecord.h"
#interface ViewController ()
{
NSString *docsDir;
NSArray *dirPaths;
NSString *databasePath;
}
#end
#implementation ViewController
#synthesize name, address,status,no;
- (void)viewDidLoad
{
[self LoadDB];
[status setHidden:TRUE];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
self.name = nil;
self.address = nil;
self.status = nil;
}
-(void)LoadDB
{
// 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:#"student.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 stud (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = #"Failed to create table";
}
else
{
status.text = #"success Created table";
}
sqlite3_close(contactDB);
}
else
{
status.text = #"Failed to open/create database";
}
}
}
- (IBAction)SaveData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO stud (name, address) VALUES (\"%#\", \"%#\")", name.text, address.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = #"Contact added";
name.text = #"";
address.text = #"";
}
else
{
status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (IBAction)UpdateData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
NSString *updateSQl=[NSString stringWithFormat:#"update stud set name=\"%#\",address=\"%#\" where id=\"%#\" ",name.text,address.text,no.text];
const char *update_stmt=[updateSQl UTF8String];
sqlite3_prepare_v2(contactDB, update_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
status.text=#"Record Updated";
name.text=#"";
address.text=#"";
no.text=#"";
}
else
{
status.text=#"Record Not Updated";
}
}
}
- (IBAction)DeleteData:(id)sender
{
[status setHidden:false];
sqlite3_stmt *statement;
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) {
NSString *deleteSql=[NSString stringWithFormat:#"delete from stud where id=\"%#\"",no.text];
const char *delete_stmt=[deleteSql UTF8String];
sqlite3_prepare_v2(contactDB, delete_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE)
{
status.text=#"Record Deleted";
name.text=#"";
address.text=#"";
no.text=#"";
}
else
{
status.text=#"Record Not Deleted ";
}
}
}
- (IBAction)ClearData:(id)sender
{
name.text=#"";
no.text=#"";
address.text=#"";
}
- (IBAction)ShowData:(id)sender
{
ShowRecord *showrecord=[[ShowRecord alloc]initWithNibName:#"ShowRecord" bundle:nil];
[self. pushViewController:showrecord animated:YES];
// ShowRecord *vc1 = [[ShowRecord alloc] initWithNibName:#"ViewControllerNext" bundle:nil];
//[self.navigationController pushViewController:vc1 animated:YES];
}
- (IBAction)FindData:(id)sender
{
[status setHidden:false];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT name,address FROM stud WHERE id=\"%#\"",
no.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *namefield=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
NSString *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
name.text=namefield;
address.text = addressField;
status.text = #"Record Found";
}
else
{
status.text = #"Record Not Found";
address.text = #"";
name.text=#"";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
#end
Related
I stored all the images in SQLiteManager for local database. I need to show all images in viewcontroller. But when i was fetching images from database it showing only one images. I don't use any webservice.
code:
SQLiteManager:
Table name: SimpleTbl
id sm descrip photo
1 sm1 ok BLOB(size:2345)
2 sm2 ok1 BLOB(size:3245)
3 sm3 ok2 BLOB(size:4535)
.h file:
#interface Mysof : NSObject{
NSInteger sofId;
NSString *sof;
NSString *rating;
UIImage *photo;
}
#property (nonatomic,retain)NSString *sofa;
#property (nonatomic, assign) NSInteger sofaId;
#property (nonatomic, retain)NSString *rating;
#property (nonatomic, retain) UIImage *photo;
.m file:
- (NSMutableArray *) getMylists{
NSMutableArray *sArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"Sample.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 SimpleTbl";
NSLog(#"sql is %s", sql);
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Mysof *Mylist = [[Mysof alloc]init];
Mylist.sofId = sqlite3_column_int(sqlStatement, 0);
Mylist.sof = [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];
[sArray addObject:Mylist];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return sArray;
}
}
Then viewcontroller i display the fetching image to imageview via button click:
-(void)click:(id)sender{
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(20, 52, 72, 72)];
// UIImageView *mmageView=[UIImageView alloc];
// [mmageView setFrame:CGRectMake(20, 52, 75, 75)];
[self.view addSubview:mmageView];
Soflistsql * mysofs =[[Soflistsql alloc] init];
self.arraysofs = [mysofs getMyLists];
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:0]).photo];
}
scrollview:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint scrollOffset=scrollView.contentOffset;
///at any time, it will have only 3 pages loaded- previous, current and next
if(pageOnScrollView < ((int)scrollOffset.x/320))
{
//unload
if(pageOnScrollView>1)[self unloadPreviousPage:pageOnScrollView-2];
[self loadNextPage:((int)scrollOffset.x/320)+1];
else if(pageOnScrollView > ((int)scrollOffset.x/320))
{
//unload
if(pageOnScrollView<(NUM_PAGES-2))[self unloadPreviousPage:pageOnScrollView+2];
[self loadNextPage:((int)scrollOffset.x/320)-1];
}
pageOnScrollView=scrollOffset.x/320;
}
-(void)unloadPreviousPage:(int)index
{
for (int index = 0; index<[self.arraysofs count]; index++ ) {
[[myScrollView viewWithTag:index+1] removeFromSuperview];
}
}
-(void)loadNextPage:(int)index
{
int countFlag=0;
for (int index = 0; index<[self.arraysofs count]; index++ ) {
NSLog(#"index %d",index);
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake((320*index)+countFlag*80+ 2, 5, 75, 75)];
[self.view addSubview:mmageView];
mmageView.tag=index+1;
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:index]).photo];
}
[myScrollView addSubview:mmageView];
countFlag++;
}
1) log the Array count and check the items count.
2) then make a for loop like this
for (int index = 0; index < [self.arraysofs count]; index ++ ) {
NSLog(#"index %d",index);
mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(20+(index*74), 52, 72, 72)];
[self.view addSubview:mmageView];
Soflistsql * mysofs =[[Soflistsql alloc] init];
self.arraysofs = [mysofs getMyLists];
[mmageView setImage:((Mysof *) [self.arraysofs objectAtIndex:index]).photo];
}
check this to add images on a scroll view Adding UIImageViews to UIScrollView
i am trying to insert values.But values are not saved.This is my coding.i alredy created the database using sqlite manager.That database name is "feedback.sqlite". If i run the code no errors will be displayed.But if i entered the data then click the save button the data will not be saved.if i run the code "Failed to open/create database" message will be displayed on the simulator.i cant guess where the error is.please give me an idea.thanks in advance.
Ratingviewcontroller.h
#interface RatingViewController : UIViewController <UITextFieldDelegate> {
sqlite3 *contactDB;
IBOutlet UITextField *Traineeid;
IBOutlet UITextField *Trainername;
IBOutlet UITextField *Traineename;
IBOutlet UITextField *Rating;
IBOutlet UILabel *status;
NSString *dbpath;
}
#property(nonatomic, retain) UITextField *Traineeid;
#property(nonatomic, retain) UITextField *Trainername;
#property(nonatomic, retain) UITextField *Traineename;
#property(nonatomic, retain) UITextField *Rating;
#property(nonatomic, retain) UILabel *status;
- (IBAction)saveData:(id)sender;
- (IBAction)findData:(id)sender;
#end
Ratingviewcontroller.m
#implementation RatingViewController
- (void)viewDidLoad {
// Do any additional setup after loading the view, typically from a nib.
NSString *docsDir;
NSArray *dirPaths;
// get the document directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
dbpath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:#"feedback.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:dbpath] == NO) {
const char *db = [dbpath UTF8String];
if (sqlite3_open(db, &contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (Traineeid INTEGER "
"PRIMARY KEY AUTOINCREMENT, Trainername TEXT, Traineename "
"TEXT, Rating float)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) !=
SQLITE_OK) {
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
[super viewDidLoad];
}
- (void)saveData:(id)sender {
sqlite3_stmt *statement;
const char *database = [dbpath UTF8String];
if (sqlite3_open(database, &contactDB) == SQLITE_OK) {
NSString *insertSQL =
[NSString stringWithFormat:
#"INSERT INTO CONTACTS (Trainee id, Trainer name, Trainee "
"name,Rating) VALUES (\"%#\",\"%#\", \"%#\", \"%#\")",
Traineeid, Trainername.text, Trainername.text, Rating.text];
/* NSString *insertSQL = [NSString stringWithFormat:#"insert into
CONTACTS
(Traineeid,Trainername,Traineename,Rating) values
(\"%d\",\"%#\", \"%#\",
\"%f\")",[Traineeid integerValue],
Trainername, Traineename,[Rating
float]];*/
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
status.text = #"Contact added";
Traineeid.text = #"";
Trainername.text = #"";
Traineename.text = #"";
Rating.text = #"";
} else {
status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (void)findContact {
const char *datapath = [dbpath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(datapath, &contactDB) == SQLITE_OK) {
NSString *querySQL = [NSString stringWithFormat:
#"select Trainer name,Trainee name,Rating "
"from CONTACT where Traineeid=\"%#\"",
Traineeid];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) ==
SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *trainid = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 0)];
Traineeid.text = trainid;
NSString *trainernme = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 1)];
Trainername.text = trainernme;
NSString *traineenme = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 2)];
Traineename.text = traineenme;
NSString *rat = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 3)];
Rating.text = rat;
status.text = #"Match found";
} else {
status.text = #"Match not found";
Traineeid.text = #"";
Trainername.text = #"";
Traineename.text = #"";
Rating.text = #"";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
try this code and also you already created the database using sqlite manager.Thats why there is no need to create the insert the values.
- (void)viewDidLoad {
if ([filemgr fileExistsAtPath:dbpath]) {
const char *db = [dbpath UTF8String];
if (sqlite3_open(db, &contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (Traineeid INTEGER "
"PRIMARY KEY AUTOINCREMENT, Trainername TEXT, Traineename "
"TEXT, Rating float)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) !=
SQLITE_OK) {
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
[super viewDidLoad];
}
Please review following code
-(void)addScrollView{
[self selectData];
scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(5, 00, 320, 480)];
int counter=5;
float y=40.0f;
int fullLength=[photoArray count];
int horizontal=320;
int vertical=(fullLength/4)*80;
int c1=1;
for(int c=0;c<[photoArray count];c++){
PhotoData *d=[photoArray objectAtIndex:c];
if(c1==5){
counter=5;
y=y+80.0f;
c1=1;
}
UIImage *img1=[[UIImage alloc]initWithContentsOfFile:d.photoPath];
UIButton* button = [[UIButton alloc] init];
button.tag=c;
[button setBackgroundImage:img1 forState:UIControlStateNormal];
[button setFrame:CGRectMake(counter, y, 70.0, 70.0)];
[button addTarget:self action:#selector(showDetail:)
forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
counter=counter+78.0f;
c1++;
[button release];
[img1 release];
[d release];
}
[scrollView setContentSize:CGSizeMake(horizontal, vertical+200)];
[self.view addSubview:scrollView];
[scrollView release];
}
-(void)selectData{
//This method is defined to retrieve data from Database
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
//Obtained the path of Documennt directory which is editable
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"memory.sql"];
//memory.sql is sqlite file which is used as local database
photoArray=[[NSMutableArray alloc]init];
NSString *dbPath=filePath;
sqlite3 *database;
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from photo where mid=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiledStatement, 1,memoryId);
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
PhotoData *data=[[PhotoData alloc]init];
int pId=sqlite3_column_int(compiledStatement, 1);
NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
[data setPhotoId:pId];
[data setPhotoPath:filePath];
[photoArray addObject:data];
[filePath release];
} // end of the while
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
tableArray=[[NSArray alloc]initWithArray:photoArray];
paths=nil;
documentsPath=nil;
filePath=nil;
dbPath=nil;
}
Some times application crashes by giving data formatter error
You should not release object that was returned by objectAtIndex: if you have not retained it. SO try to remove line:
[d release];
You should release that object after adding it to photoArray. Do it after line :
[photoArray addObject:data];
[data release];
You should do that because your data object is not autoreleased (PhotoData *data=[[PhotoData alloc]init];) and after adding it to photoArray it is automatically retained.
I have the following problem while i scroll the table view:
NSCFString objectAtIndex:]: unrecognized selector sent to instance
I create NSDictionary tableContents and when i scroll it becomes deallocated.
This is my code:
- (void)viewDidLoad {
lessonsInGroup1 = [NSMutableArray array];
lessonsInGroup2 = [NSMutableArray array];
lessonsInGroup1 = [self grabRowsInGroup:#"1"];
lessonsInGroup2 = [self grabRowsInGroup:#"2"];
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:lessonsInGroup1,#"General Information",lessonsInGroup2,#"LaTeX Examples", nil];
//[[tableContents alloc] init];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[lessonsInGroup1 release];
[lessonsInGroup2 release];
//[table reloadData];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
- (NSMutableArray *) grabRowsInGroup:(NSString*)GroupID{
NSMutableArray *groupOfLessons;
groupOfLessons = [[NSMutableArray alloc] init];
char *sqlStatement;
int returnCode;
sqlite3_stmt *statement;
NSString *databaseName;
NSString *databasePath;
// Setup some globals
databaseName = #"TexDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
fprintf(stderr, "Error in opening the database. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
sqlStatement = sqlite3_mprintf(
"SELECT * FROM Lessons WHERE LessonGroup = '%s';", [GroupID UTF8String]);
returnCode =
sqlite3_prepare_v2(database,
sqlStatement, strlen(sqlStatement),
&statement, NULL);
if(returnCode != SQLITE_OK) {
fprintf(stderr, "Error in preparation of query. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
returnCode = sqlite3_step(statement);
while(returnCode == SQLITE_ROW) {
NSString *aLessonID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *aLessonGroup = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSString *aLessonTopic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSString *aLessonText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
NSString *aLessonCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
NSString *aLessonPicture = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
/*NSLog(aLessonID);
NSLog(aLessonGroup);
NSLog(aLessonTopic);
NSLog(aLessonText);
NSLog(aLessonCode);
NSLog(aLessonPicture);*/
// Create a new busCit object with the data from the database
Lesson *lesson = [[Lesson alloc] initWithLessonID:aLessonID LessonGroup:aLessonGroup LessonTopic:aLessonTopic LessonText:aLessonText LessonCode:aLessonCode LessonPicture:aLessonPicture];
[groupOfLessons addObject:lesson];
returnCode = sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_free(sqlStatement);
return [groupOfLessons autorelease];
}
What does your #property for tableofContents look like?
Also, you are going to run into issues with
[lessonsInGroup1 release];
[lessonsInGroup2 release];
because you are autoreleasing those in the grabRowsInGroup:
So, you don't need to call release them.
Looks like you are calling objectAtIndex on NSString. It should rather be some array
I use the code below to insert data into my sqlite-database but for some reason the application always crashes as soon as the method gets called and the problem seems to be the "sqlite3_open" statement. Does anyone have any idea what I might be doing wrong?
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Animals";
animalsArray = [[NSMutableArray alloc] init];
animalDetailController = [[AnimalDetailViewController alloc] init];
addAnimalController = [[AddAnimalViewController alloc] init];
addAnimalController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addAction)];
self.navigationItem.rightBarButtonItem = addItem;
databaseName = #"AnimalDatabase.sql";
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentsPath objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[self readDataFromDatabase];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)addAction{
[self presentModalViewController:addAnimalController animated:YES];
}
- (void)checkAndCreateDatabase{
BOOL databaseIsSaved;
NSFileManager *fileManager = [NSFileManager defaultManager];
databaseIsSaved = [fileManager fileExistsAtPath:databasePath];
if (databaseIsSaved == YES) {
return;
}
else {
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
[fileManager release];
}
- (void)readDataFromDatabase{
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select * from animals";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
[animalsArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)], #"name", [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)], #"description", nil]];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
- (void)writeToDatabase{
sqlite3 *database;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into animals(name, description) VALUES(?, ?)";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK){
sqlite3_bind_text(compiledStatement, 1, [addAnimalController.animalName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [addAnimalController.animalDescription UTF8String], -1, SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Error: %s", sqlite3_errmsg(database) );
} else {
NSLog( #"Insert into row id = %d", sqlite3_last_insert_rowid(database));
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (addAnimalController.saveButtonPressed == YES && [addAnimalController.animalName length] != 0 && [addAnimalController.animalDescription length] != 0) {
[animalsArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:addAnimalController.animalName, #"name", addAnimalController.animalDescription, #"description", nil]];
[self.tableView reloadData];
[self writeToDatabase];
addAnimalController.saveButtonPressed = NO;
}
}
You need a retain when you set databasePath.
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
Should be
databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
Make sure you release it in your viewDidUnload and dealloc implementations. (It's probably smart to release it before you set it as well.)
Probably has nothing to do with this function. I wrote this blog to help understand EXC_BAD_ACCESS
http://www.loufranco.com/blog/files/Understanding-EXC_BAD_ACCESS.html
You should turn on Zombies and see if you are over-releasing any objects.