I'm almost done with this project. I have created a small application of a phone book using SQLite. I'm facing a thread error after the successful build. In gist i'll tell you what i'm upto in this project. I have created a simple phonebook in which you can add Name, number and address of the person. There are two buttons to save and find the contacts. All the status are print in label. I have included and imported libsqlite3.dylib into the project. Once the build was done. I got a thread error in the main class stating libc++abi.dylib: terminate called throwing an exception.
Any help? I'm almost done with this project.
my viewcontroller.h looks like this:
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *address;
#property (strong, nonatomic) IBOutlet UITextField *phone;
#property (strong, nonatomic) IBOutlet UILabel *status;
- (IBAction)saveData:(id)sender;
- (IBAction)findContact:(id)sender;
#property (strong, nonatomic) NSString *databasePath;
#property (nonatomic) sqlite3 *contactDB;
#end
and my viewcontroller.m looks like this:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super 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:
#"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, ADDRESS TEXT, PHONE TEXT)";
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";
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveData:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
self.name.text, self.address.text, self.phone.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
self.status.text = #"Contact added";
self.name.text = #"";
self.address.text = #"";
self.phone.text = #"";
}
else
{
self.status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
- (IBAction)findContact:(id)sender
{
const char *dbpath = [_databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT address, phone FROM contacts WHERE name=\"%#\"",
_name.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 *addressField = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
_address.text = addressField;
NSString *phoneField = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
_phone.text = phoneField;
_status.text = #"Match found";
}
else
{
_status.text = #"Match not found";
_address.text = #"";
_phone.text = #"";
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
}
#end
in your imports statement in ".h" file, have this instead:
#import "/usr/include/sqlite3.h"
You must specify the complete path for sqlite3 header file.
Related
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];
}
Below is my code to store images in the sqlite database. When I used it to store values it works and now I'm trying to store images in sqlite database. I don't know what I'm doing wrong. I already searched and I can't get the answer what I need. Anyone help me with his code.
sqlite3 *database;
dbName=#"dataTable.sqlite";
NSArray *documentpath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdir=[documentpath objectAtIndex:0];
dbPath=[documentdir stringByAppendingPathComponent:dbName];
sqlite3_stmt *compiledStmt;
if(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK){
NSLog(#"Name:%#,Company:%#,URL:%#",model.personName,model.companyName,model.imgurl);
const char *insertSQL="insert into Persons(PersonName,CompanyName,ImgUrl,PersonImage)values(?,?,?,?)";
if(sqlite3_prepare_v2(database,insertSQL, -1, &compiledStmt, NULL)==SQLITE_OK){
sqlite3_bind_text(compiledStmt,1,[model.personName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStmt,2,[model.companyName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStmt,3,[model.imgurl UTF8String],-1,SQLITE_TRANSIENT);
NSData *imageData=UIImagePNGRepresentation(imageView.image);
sqlite3_bind_blob(compiledStmt, 4, [imageData bytes], [imageData length], NULL);
NSLog(#"Prepare");
sqlite3_step(compiledStmt);
}sqlite3_finalize(compiledStmt);
}
UPDATE:
Thanks to everyone.. I cleared this issue by asked another question from here.. store and retrieve image into sqlite database for iphone This may help to others.
const char *insertSQL="insert into Persons(PersonName,CompanyName,ImgUrl,PersonImage)values(?,?)"
You have 4 values to insert into your table & only 2 placeholders for the parameters. Correct them.
Heck I ain't an iOS developer
you just ADD libSqlite3.dylib to Linked FrameWork and Lilbraries and declared database varibles in .h file
//Database Variables
#property (strong, nonatomic) NSString *databasePath;
#property (nonatomic)sqlite3 *contactDB;
#property (strong, nonatomic) IBOutlet UIButton *backbtn;
#property (strong, nonatomic) IBOutlet UIButton *forwardbtn;
drag and drop UIImageView and name to that... i declared as imgView.
Goto .m file you just copy and paste that code
int i=1;
long long temp=0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
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: #"images.db"]];
//docsDir NSPathStore2 * #"/Users/gayathiridevi/Library/Application Support/iPhone Simulator/7.0.3/Applications/B5D4D2AF-C613-45F1-B414-829F38344C2A/Documents" 0x0895e160
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 IMAGETB (ID INTEGER PRIMARY KEY AUTOINCREMENT,URL TEXT, CHECKSUM TEXT,IMAGE BLOB)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog( #"User table Not Created Error: %s", errMsg);
}
else
{
NSLog( #"User table Created: ");
}
sqlite3_close(_contactDB);
}
else {
NSLog( #"DB Not Created");
}
}
[self saveImage];
[self showImage];
}
- (void)saveImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL=#"INSERT INTO IMAGETB(URL,image) VALUES(?,?)";
if(sqlite3_prepare_v2(_contactDB, [insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL)== SQLITE_OK)
{
//NSString *url =#"https://lh6.googleusercontent.com/-vJBBGUtpXxk/AAAAAAAAAAI/AAAAAAAAADQ/nfgVPX1n-Q8/photo.jpg";
//NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/2/2a/Junonia_lemonias_DSF_upper_by_Kadavoor.JPG";
// NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/8/84/Tibia_insulaechorab.jpg";
NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/PNG_transparency_demonstration_2.png/280px-PNG_transparency_demonstration_2.png";
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
NSData *imageData=UIImagePNGRepresentation(image);
sqlite3_bind_text(statement,1, [url UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
NSLog(#"Length from internet : %lu", (unsigned long)[imageData length]);
}
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog( #"Insert into row id %lld",(sqlite3_last_insert_rowid(_contactDB)));
temp =(sqlite3_last_insert_rowid(_contactDB));
}
else {
NSLog( #"Error IN INSERT" );
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
- (void)showImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if(sqlite3_open(dbpath,&_contactDB)==SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"Select IMAGE FROM IMAGETB WHERE ID = %d",i];
if(sqlite3_prepare_v2(_contactDB,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
int length = sqlite3_column_bytes(statement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
NSLog(#"Length from db : %lu", (unsigned long)[imageData length]);
if(imageData == nil)
NSLog(#"No image found.");
else
_imgView.image = [UIImage imageWithData:imageData];
NSLog(#"image found.");
}
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
-(IBAction)backBtn:(id)sender {
if (i<=1) {}
else{
i=i-1;
[self showImage];
}
}
-(IBAction)forwardBtn:(id)sender {
if(i==temp){}
else{
i=i+1;
[self showImage];
}
}
I answered a similair question with this answer: It's better if you use CoreData instead. It will be much easier for you to work with CoreDate instead of SQL. CoreData is pretty much an SQL database in a nice wrapper.
If you use iOS 5 you could easily add images to the database without having to worry about them being BLOBS (Binary Large Object) by checking "Allows External Storage".
You should check the return values of bind_text and bind_blob and the step-call, print an error message when they fail.
I am making an registration form in which i have two pages to complete the registration process.
page1 contains:
i have 8 textfield and one submit button in page 1...
when ever user enter the value in textfield and click the submit button all the enter value in textfield should get insert in my sqlite table and move to the next page with the same value in textfield .
page 2 contains
i have 8 textfield and two button:Edit, and continue in page 2...
this page should contains all the page1 textfield value in it,so that he can check the value enter by him are correct or not,and if not then he should be able to edit them and save them and proceed further.....
below is my page 1 code:
.h file
#import <UIKit/UIKit.h>
#import "/usr/include/sqlite3.h"
#import "Confirmation_form.h"
#interface Registration_Form :
UIViewController<UITextFieldDelegate> {
Confirmation_form *con_form;
sqlite3 *test1DB;
IBOutlet UITextField *UserName;
IBOutlet UITextField *Password;
IBOutlet UITextField *ConfirmPassword;
IBOutlet UITextField *Name;
IBOutlet UITextField *Email;
IBOutlet UITextField *ContactNO;
IBOutlet UITextField *MobileNo;
IBOutlet UITextField *Address;
NSString *databasePath;
}
#property(nonatomic,retain)IBOutlet UITextField *UserName;
#property(nonatomic,retain)IBOutlet UITextField *Password;
#property(nonatomic,retain)IBOutlet UITextField *ConfirmPassword;
#property(nonatomic,retain)IBOutlet UITextField *Name;
#property(nonatomic,retain)IBOutlet UITextField *Email;
#property(nonatomic,retain)IBOutlet UITextField *ContactNO;
#property(nonatomic,retain)IBOutlet UITextField *MobileNo;
#property(nonatomic,retain)IBOutlet UITextField *Address;
-(IBAction) submit;
this is my .m file:
#import "Registration_Form.h"
#implementation Registration_Form
#synthesize UserName,Password,ConfirmPassword,Name,Email,ContactNO,MobileNo,Address;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"test1.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if(sqlite3_open(dbpath, &test1DB) ==SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS test (ID INTEGER PRIMARY KEY AUTOINCREMENT, USERNAME TEXT, PASSWORD TEXT, CONFIRMPASSWORD TEXT, NAME TEXT, EMAIL TEXT, CONTACTNO MUMBER, MOBILENO NUMBER,ADDRESS TEXT)";
if(sqlite3_exec(test1DB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
//status.text = #"Failed to create table";
}
sqlite3_close(test1DB);
}else {
//status.text = #"Failed to open/create database";
}
}
[filemgr release];
[super viewDidLoad];
}
-(void)submit
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &test1DB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO test(UserName,
Password, ConfirmPassword, Name, Email, ContactNO, MobileNo, Address) VALUES (\"%#\", \"%#\",
\"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\")",UserName.text, Password.text, ConfirmPassword.text,
Name.text, Email.text, ContactNO.text, MobileNo.text, Address.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(test1DB, insert_stmt, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE)
{
//status.text = #"Contact added";
UserName.text = #"";
Password.text = #"";
ConfirmPassword.text = #"";
Name.text = #"";
Email.text = #"";
ContactNO.text = #"";
MobileNo.text = #"";
Address.text = #"";
}else {
//status.text = #"Failed to add Contact";
}
sqlite3_finalize(statement);
sqlite3_close(test1DB);
}
con_form = [[Confirmation_form alloc] initWithNibName:#"Confirmation_form" bundle:[NSBundle
mainBundle]];
[self.navigationController pushViewController:con_form animated:YES];
}
please help me out
thank's
First of all you have create NSString object and their property in your 1stcontroller than after store the text filed value in this NSString .eg.passstring = UserName.text;
Than after pass this string to the next 2ndcontroller .
By creating the the object of 1stcontroller.like this 1stcontroller *urobject = [[1stcontroller alloc]init];
yourtextfiled = urobject.passstring;
i hope this will help you
Great tutorial on pure sqlite here.
But I would suggest just using properties unless that data is needed past the second form.
Also, if you are going to be doing a lot of db work I would suggest FMDatabase.
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
}
}
I have the following function but I don't know how to release the memory of the temporary object defined:
#import <UIKit/UIKit.h>
#interface PatientsSet : NSObject {
NSString *tableid;
NSString *patient_name;
NSString *patient_surname;
NSString *city;
NSString *State;
NSString *phone;
}
#property (nonatomic, retain) NSString *tableid;
#property (nonatomic, retain) NSString *patient_name;
#property (nonatomic, retain) NSString *patient_surname;
#property (nonatomic, retain) NSString *city;
#property (nonatomic, retain) NSString *State;
#property (nonatomic, retain) NSString *phone;
-(id)initWithSet:(NSString *)dd patient_name:(NSString *)dn patient_surname:(NSString *)dsn city:(NSString *)ct state:(NSString *)st phone:(NSString *)ph ;
#end
(I'm getting from the a SQLITE DB the data into a NSobject derived class)
Shouldn't I use a [set release]; somewhere??
-(PatientsSet *)getPatientById:(NSString *)ID {
PatientsSet *set;
// Setup the database object
sqlite3 *database;
// Init the doctors_set Array
doctors_set = [[NSMutableArray alloc] init];
//NSString * databasePath1=[ [self getDocumentsDirectory] stringByAppendingPathComponent:databaseName ];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
NSString* myString = [NSString stringWithFormat:#"SELECT patients.id,patients.patient_name,patients.patient_surname,patients.phone FROM patients where patients.id = '%#'",ID];
const char *sqlStatement = [myString cString];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDurname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aPhone = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new set object with the data from the database
set=[[PatientsSet alloc] initWithSet:aId patient_name:aName patient_surname:aDurname city:#"" state:#"" phone:aPhone];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return set;
}
You need to return an autoreleased object like so:
return [set autorelease];