How to insert values using sqlite in iphone - iphone

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];
}

Related

Phonebook iOS app using sqlite

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.

not able to insert record in table in objective c

I made iPad application in which,
I want to insert record into database table, but I am unable to do the same.
here is my code snippet,
-(void) insertRecordIntoTableNamed: (NSString *) symbol{
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
NSLog(#"sql=%#",sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0, #"Error updating table.");
}
}
my NSLog shows:
sql=INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('PATNI',datetime())
this statement is correct, but i am unable to see VALUES PATNI and datetime() in my database table
here is rest of the code,
NSString *filePahs = Nil;
-(NSString *) filePath {
filePahs=[[NSBundle mainBundle] pathForResource:#"companymaster" ofType:#"sql"];
NSLog(#"path=%#",filePahs);
return filePahs;
}
result of above method is:
path=/Users/krunal/Library/Application Support/iPhone Simulator/5.0/Applications/9FF61238-2D1D-4CB7-8E24-9AC7CE9415BC/iStock kotak.app/companymaster.sql
-(void) openDB {
//---create database---
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK )
{
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
-(void) getAllRowsFromTableNamed: (NSString *) tableName {
//---retrieve rows---
NSString *qsql = #"SELECT * FROM recentquotes";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) ==
SQLITE_OK) {
NSLog(#"b4 while");
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
[field1Str release];
}
//---deletes the compiled statement from memory---
sqlite3_finalize(statement);
NSLog(#"recentqotarray=%#",recentqotarray);
}
}
edit
i wrote this, and when i checked my log i got like this, "in find data" , i didn't got my sql=...
- (void) finddata
{
NSString *databasePath;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"in finddata");
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM recentquotes"];
NSLog(#"sql=%#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Inside recent quote table");
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSLog(#"Column name=%s",field1);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
NSLog(#"array=%#",recentqotarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
Thanks In Advance
In your:
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
Instead of '%#' try using \"%#\" , and check if it inserts into your db.
EDIT:
I've been working on DB a lot lately, and i've been able to successfully insert data in my sqlite, i'll write down what i use check if it helps:
NSArray*dirPath;
NSString*docDir;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:#"example.sqlite"];
BOOL success;
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Already present");
}
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"example" ofType:#"sqlite"];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(#"Created successfully");
}
const char*dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &myDB)==SQLITE_OK)
{
NSString*insertSQL=[NSString stringWithFormat:#"insert into extable (name) values (\"%#\")",[nametextField.text]];
const char*insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(myDB, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"ADDED!");
}
sqlite3_close(myDB);
}

store images into sqlite database

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.

SQLite sqlite3_prepare_v2 no error but not ok neither

Hey guys, I'm just playing around with SQLite so this is new for me. I've got a view in which persons data can be both saved and found. The save-function and find-function work perfectly. Now, I've got a new view with a tableView in it. I want to get all the persons in the contacts-table and fill the list with it.
Untill now, I've got:
-(void)viewWillAppear:(BOOL)animated {
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"Opened DB");
NSString *querySQL = [NSString stringWithFormat:#"SELECT name FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
NSLog(#"could not prepare statement: %s\n", sqlite3_errmsg(contactDB));
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
//if (sqlite3_step(query_stmt) == SQLITE_DONE)
{
//NSLog(#"SQLite OK");
NSLog(#"SQLite ok");
//if (sqlite3_step(statement) == SQLITE_ROW)
//{
while(sqlite3_step(statement) == SQLITE_ROW) {
NSLog(#"SQLite ROW");
NSString *person = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[personsList addObject:person];
}
//} else {
// NSLog(#"Emtpy list");
//}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
NSLog(#"Calling reload");
NSLog(#"%#", personsList);
[tabelView reloadData];
}
This is all in viewWillAppear. When the view is loaded and done, the log says:
2011-05-06 10:45:26.976 database[1412:207] Opened DB
2011-05-06 10:45:26.978 database[1412:207] could not prepare statement: not an error
2011-05-06 10:45:26.979 database[1412:207] Calling reload
2011-05-06 10:45:26.979 database[1412:207] (
)
So it seems the statement isn't an error, but sqlite3_prepare_v2 isn't SQL_OK after all. Any help?
EDIT: In the previous view, the statement for creating a person is: #"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")", name.text, address.text, phone.text];
The statement for finding someone is: #"SELECT address, phone FROM contacts WHERE name=\"%#\"", name.text];
These two statements work and the data is displayed.
#joetjah I used your code to fetch the results and it worked fine
2011-05-06 16:03:00.076 SQLiteDemo[6454:207] Opened DB
2011-05-06 16:03:09.550 SQLiteDemo[6454:207] could not prepare statement: not an error
2011-05-06 16:03:24.685 SQLiteDemo[6454:207] SQLite ok
2011-05-06 16:03:26.229 SQLiteDemo[6454:207] SQLite ROW
2011-05-06 16:03:28.254 SQLiteDemo[6454:207] SQLite ROW
2011-05-06 16:03:34.461 SQLiteDemo[6454:207] Calling reload
2011-05-06 16:03:35.009 SQLiteDemo[6454:207] (
rahul,
sqlite
)
-(void)testFunction{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
sqlite3 *contactDB;
NSMutableArray *personsList = [[NSMutableArray alloc ] initWithCapacity:0];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"Opened DB");
NSString *querySQL = [NSString stringWithFormat:#"SELECT name FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
NSLog(#"could not prepare statement: %s\n", sqlite3_errmsg(contactDB));
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
//if (sqlite3_step(query_stmt) == SQLITE_DONE)
{
//NSLog(#"SQLite OK");
NSLog(#"SQLite ok");
//if (sqlite3_step(statement) == SQLITE_ROW)
//{
while(sqlite3_step(statement) == SQLITE_ROW) {
NSLog(#"SQLite ROW");
NSString *person = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[personsList addObject:person];
}
//} else {
// NSLog(#"Emtpy list");
//}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
NSLog(#"Calling reload");
NSLog(#"%#", personsList);
//[tabelView reloadData];
}
You can compare the code, The probable point of failure might be
1] data not being saved properly and hence nothing is fetched.
2] databasePath being set to blank (which I doubt as you get Open Db log)
The table contact is created using "CREATE TABLE contacts (name text, age integer)"
try this once and let me know if it works.
Try this,
-(void)viewWillAppear:(BOOL)animated {
// Override point for customization after app launch.
// Setup some globals
// 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:#"contacts.db"];
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"Opened DB");
NSString *querySQL = [NSString stringWithFormat:#"SELECT name FROM CONTACTS"];
const char *query_stmt = [querySQL UTF8String];
NSLog(#"could not prepare statement: %s\n", sqlite3_errmsg(contactDB));
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"SQLite ok");
while(sqlite3_step(statement) == SQLITE_ROW) {
NSLog(#"SQLite ROW");
NSString *person = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[personsList addObject:person];
}
sqlite3_finalize(statement);
}
else
{
//NSLog(#"could not prepare statement: %s\n", sqlite3_errmsg(statement));
}
sqlite3_close(contactDB);
}
NSLog(#"Calling reload");
NSLog(#"%#", personsList);
[tabelView reloadData];
}
I used const char *dbpath = [databasePath UTF8String];, but I forgot to put the following code above it:
// Get the documents directory
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"contacts.db"]];
const char *dbpath = [databasePath UTF8String];
This worked for me:
create the table in your didload functions and then add this in (assuming you have declared the other table view functions):
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
var selectStatement: OpaquePointer? = nil
let selectSql = "select * from Inventory where ID = \((indexPath.row + 1))"
if sqlite3_prepare_v2(Database.database.sqliteDB, selectSql, -1, &selectStatement, nil) == SQLITE_OK{
if sqlite3_step(selectStatement) == SQLITE_ROW {
let nameItem = sqlite3_column_text(selectStatement, 1)
let price = sqlite3_column_double(selectStatement, 2)
let quantity = sqlite3_column_int(selectStatement, 3)
let nameString = String(cString: nameItem!)
let priceString = String(format: "%.1f",price)
let quantityString = String(quantity)
cell.itemName.text = nameString
cell.itemPrice.text = priceString
cell.itemQuantity.text = quantityString
}
}
return cell
}

how to connect with sqlite in iphone? [closed]

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