How to store data in database(sqlite) - ios

On iOS, I want store user data in database using sqlite. For that design .Xib file username, password, DOB as text fields and take button, after fill all text fields when click the button all the data is stored in database.

I assume you already know how outlets work and how to get information from UI elements.
SQLite part. SQLite is very easy. You need to have an INSERT query, like this:
char *query = "INSERT INTO myTable (field1, field2) VALUES (?, ?)";
sqlite3_stmt *statem;
sqlite3_prepare_v2(myDB, query, -1, &statem, NULL);
sqlite3_bind_text(statem, 1, [[field1 text] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statem, 2, [[field1 test] UTF8String], -1, SQLITE_STATIC);
do {
int status = sqlite3_step(statem);
} whlie (status != SQLITE_DONE && status != SQLITE_ERROR);
You should set up the DB first but this can all be found in the documentation.

Related

Why I am Not able to create and add data to the sqlite file at the same time?

In My current ios application I have to add tables and insert data to the added table for new version.
By taking Upgrade into consideration I did it through the code itself Like below
-(void)lessThan100TableQuery
{
NSString *query=[NSString stringWithFormat:#"CREATE TABLE 'Table_Name' ('item_id' INTEGER PRIMARY KEY NOT NULL , 'item_section' INTEGER, 'item_no' INTEGER, 'bullet_no' VARCHAR, 'heading' INTEGER, 'hide_controls' INTEGER, 'description' VARCHAR);INSERT INTO 'Table_Name' VALUES(1,1,0,'',1,1,'Condition/adequacy of distributor''s/supply intake equipment');"
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
if(sqlite3_step(statement) != SQLITE_DONE) {
return NO;
}
sqlite3_finalize(statement);
}
}
(like above I add 100 rows I skipped them here)
But by calling the above method only the table get added without the values
I cross checked it by running the above query in sqlitemanager and working fine without any issue. It is not working in code.
Help me out folks
The sqlite3_prepare_v2() documentation says:
These routines only compile the first statement in zSql
To execute multiple statements, you have to use a loop, and use pzTail to skip over the previously-executed statement.

Update Data Into SQLite Database

I want to update the data into sqlite db.I tried and followed lot of links and methods for update data.But all these do not work out for me.
when i insert my data, following data inserted in db with no problem.
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO BusinessCardAppOneTable (NamorTitofImginTxtFld ,TxtofTxtView ,ImaGe,Location,Date,Time)VALUES(?,?,?,?,?,?);"];
NOTE:For image i created the image folder(path) in DB.
Then i fetched and i displayed these data from DB to tableview.
Then i edited NamorTitofImginTxtFld,TxtofTxtView,Date,Time (These are in edit view controller-where i get the image,location,date,time,NamorTitofImginTxtFld,TxtofTxtView from tableview(fetch data))
After that i edited NamorTitofImginTxtFld,TxtofTxtView,date and time.Also if i want to set the date and time i should go to REMAINDER VIEW CONTROLLER(from remainder button of edit view controller to remainder view controller).Where i set the date and time picker.Once i set that and back to edit view controller i can see the edited part.
So my update query is
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE BusinessCardAppOneTable SET NamorTitofImginTxtFld = ?, TxtofTxtView = ?,Date = ? WHERE Time =? "];
If i only edited NamorTitofImginTxtFld and TxtofTxtView,these only updated in db.But if i edited all NamorTitofImginTxtFld , TxtofTxtView with date and time all these do not update.
Anyone can explain about the database update and how to update these 4 columns in db successfully?
I submitted the 3 various options
first //it match up ur answer
update BusinessCardAppOneTable set NamorTitofImginTxtFld = ?, TxtofTxtView = ?, Date = ?, Time =? where id = 5 // here u need to identify your id, if it is correct it surely update
second //it is related to your answer
Yes You can use Parametrized Query as Below :-
NSString *sqlString = #"update BusinessCardAppOneTable set NamorTitofImginTxtFld = ?, TxtofTxtView = ?, Date = ?, Time =? where id = ?";
sqlite3_stmt *stmt;
if(sqlite3_prepare(database, [sqlString UTF8String], -1, &stmt, NULL) != SQLITE_OK)
{
//Handle Error
}
if(sqlite3_bind_text(stmt, 1, [record.name UTF8String],[record.type UTF8String],[record.state UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK)
{
// Handle Error
}
if(sqlite3_bind_int(stmt, 2, record.key) != SQLITE_OK)
{
// Handle Error
}
if (sqlite3_step(statement) != SQLITE_DONE)
{
// Handle Error
}
And your Parametrized Code is ready.
in third choice
u follow the link Sqlite3 update query not working in ios app

How to check and then insert in sqlite?

I have a area table in sqlite database. Everytime i am just performing insert operation onto the sqlite database. How can i check if any record exists or not. If not exist simply insert. If exist then update records.
Please help me.
you can do easily "insert or ignore into tbl_name"
here you can see the example
http://www.raywenderlich.com/913/sqlite-tutorial-for-ios-making-our-app
this would be usefull for you....
http://www.sqlite.org/lang_conflict.html
Yes, you can do that with a single query.
INSERT ON CONFLICT IGNORE should help you: http://www.sqlite.org/lang_conflict.html
Put a unique key on the name, this will create a conflict when you try inserting a record if the name already exists.
The default is ABORT, so without the IGNORE, the statement will return an error. If you don't want that, use IGNORE.
You can do INSERT OR REPLACE if you have a primary key on the table. For example:
sqlite3 *database = NULL;
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingPathComponent:#"test.sqlite"];
int rc = sqlite3_open([path UTF8String], &database);
NSAssert(rc == SQLITE_OK, #"Open failed");
// note, use PRIMARY KEY when creating table
rc = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS test (animal TEXT PRIMARY KEY, sound TEXT)", NULL, NULL, NULL);
NSAssert(rc == SQLITE_OK, #"Create failed: %s", sqlite3_errmsg(database));
// create a record that will be replaced by the subsequent `INSERT OR REPLACE`
rc = sqlite3_exec(database, "INSERT INTO test (animal, sound) VALUES ('dog', 'meow')", NULL, NULL, NULL);
NSAssert(rc == SQLITE_OK, #"INSERT failed: %s", sqlite3_errmsg(database));
// this will REPLACE entry if value with same PK found, otherwise it would INSERT
rc = sqlite3_exec(database, "INSERT OR REPLACE INTO test (animal, sound) VALUES ('dog', 'woof')", NULL, NULL, NULL);
NSAssert(rc == SQLITE_OK, #"INSERT failed: %s", sqlite3_errmsg(database));
// now retrieve values and make sure it worked like we thought it would
sqlite3_stmt *statement = NULL;
rc = sqlite3_prepare_v2(database, "SELECT animal, sound FROM test", -1, &statement, NULL);
NSAssert(rc == SQLITE_OK, #"prepare SELECT failed: %s", sqlite3_errmsg(database));
while ((rc = sqlite3_step(statement)) == SQLITE_ROW) {
const unsigned char *animal = sqlite3_column_text(statement, 0);
const unsigned char *sound = sqlite3_column_text(statement, 1);
NSLog(#"%s goes %s", animal, sound);
}
NSAssert(rc == SQLITE_DONE, #"step failed: %s", sqlite3_errmsg(database));
sqlite3_finalize(statement);
sqlite3_close(database);
And that will report that the INSERT OR REPLACE replaced the previous value rather than inserting second record:
2013-11-21 08:59:25.285 AnimalSounds[53549:70b] dog goes woof
If you don't have primary key, rather than this simple INSERT OR REPLACE, you'd have to break it into two steps, either:
Look for record with SELECT: If found, do UPDATE; if not found, do INSERT.
First DELETE any records that would match whatever criteria you want, and then do INSERT.
This first approach is a bit safer, but you could use the second approach if you had to (though you would probably use transactions a do a ROLLBACK if you had any problems). Needless to say, the INSERT OR REPLACE approach is even easier, but requires a primary key.
First call get record query in Database. Here I am add a example, I am checking that user login information available in database or not. So add below code. IF User record is available than i get record array otherwise nil.
+(NSArray*)getTBL_LOGIN
{
NSMutableArray *Favourite=[[NSMutableArray alloc]init];
sqlite3 *database;
TabBarAppDelegate *x=(TabBarAppDelegate*)[[UIApplication sharedApplication]delegate];
if(sqlite3_open([[x dataBasePath] UTF8String],&database) == SQLITE_OK) {
NSString *str = [NSString stringWithFormat:#"select * from tbl_login"];
const char *sqlStmt=[str UTF8String];
sqlite3_stmt *compiledStmt;
if(sqlite3_prepare_v2(database, sqlStmt, -1, &compiledStmt, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStmt)==SQLITE_ROW)
{
NSString *uid=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStmt, 0)];
NSString *username=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStmt, 1)];
NSDictionary *d=[NSDictionary dictionaryWithObjectsAndKeys:uid,#"uid",username,#"username",nil];
[Favourite addObject:d];
}
}
sqlite3_finalize(compiledStmt);
}
sqlite3_close(database);
if([Favourite count]>0)
{
NSArray *ar=[NSArray arrayWithArray:Favourite];
return ar;
} else {
return nil;
}
}
If you get the record count >=1 then record exist so you have to call update query if you get record count 0 than record is not available in database so you have to call insert query
In a situation where I imported all updates into another database table, I could use following:
-- Existing table: t(uc UNIQUE, v1, v2, v3);
-- Updates table: ut(uc UNIQUE, v2);
INSERT OR REPLACE INTO t
SELECT ut.uc, et.v1, ut.v2, et.v3 FROM ut
LEFT JOIN t AS et ON ut.uc=et.uc;
This statement will insert new rows from ut into t. Existing rows are replaced with a row containing new data from ut and existing data from t.
For this to work, you must have a UNIQUE column (which makes sense as you are looking for a row update or insert a new one), and have new data available so it can be queried (in same or another database).
This worked for me, hope it may help you.
Another solution, maybe with better performance is using two statements:
UPDATE t SET v1='some value', v2=123 WHERE unique_col='some_id';
INSERT OR IGNORE t(v1, v2, unique_col) VALUES('some value', 123, 'some_id');
UPDATE will become a null operation when 'some_id' is not found.
INSERT will ignore all existent 'some_id'.

Change Data of database

I'm developing for iOS and I have a previous database really poorly constructed. Now there is already 140 sealed but in my update I make a new database but I can not delete the data... How can I change the data from database A to database B ? I use sqlite3 in xCode 5
Here is an example code altering a column in a database table:
- (void)alterDB {
sqlite3_stmt *statement;
sqlite3_stmt *selectStmt;
const char *columnExists = "select callCount from lastCall";
//Alter the table ONLY IF column we want doesn't exist
if (sqlite3_prepare_v2(database, columnExists, -1, &selectStmt, NULL) != SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"ALTER TABLE lastCall ADD COLUMN callCount INTEGER"];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"DATABASE ALTERED");
} else {
NSLog(#"error altering database");
}
}
}
I hope this gives you an idea.
Write migration code,
that will select the data from Database A and will insert it into Database B.
When dealing with different schemas, I have a method that I always call when opening the database that checks the schema version in a table set aside for that purpose and then doing any alterations as needed to the schema.
- (void) checkSchema {
if([[self preferenceForKey:#"SchemaVersion"] isEqualToString: #"1"]) {
[db sqlExecute:#"create table Documents(documentID int, description text, type text, url text, modifiedDate text, read int, fileName text, needsUpdate int, primary key(documentID,type));"];
[self setPreference:#"2" ForKey:#"SchemaVersion"];
}
// etc.
}
So while developing, I can add schema changes and no matter what version of the app someone is using, when they upgrade they will get the latest schema changes.
It is because of this, and the work of changing all my accessor methods to the database that I am now using SimpleDB (https://github.com/AaronBratcher/SimpleDB), a key/value db I wrote. Completely different way of accessing data that makes things a lot simpler.

SQLite Update Statement Possibilities in iOS SQLite3

My iOS app uses SQLite3 databases and so far I have successfully managed to create tables, insert values and then later select them.
However, now I want to update. I tried this:
UPDATE field WHERE _id = 5 (name,type,state) VALUES (?,?,?)
But SQLite tells me a syntax error exists near the WHERE
As I understand that SQLite may not support the above syntax preferring it formatted as below.
UPDATE field SET name= "Upper" type= "Pigs" state=1 WHERE _id = 5;
However notice in the second statement there are no (?,?,?) (parameterized query I believe its called) for dynamically inserting values into the SQL string. Tell me is this possible and if so how?
Yes You can use Parametrized Query as Below :-
NSString *sqlString = #"UPDATE field SET name=?, type=?, state=? where _id=?";
sqlite3_stmt *stmt;
if(sqlite3_prepare(database, [sqlString UTF8String], -1, &stmt, NULL) != SQLITE_OK)
{
//Handle Error
}
if(sqlite3_bind_text(stmt, 1, [record.name UTF8String],[record.type UTF8String],[record.state UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK)
{
// Handle Error
}
if(sqlite3_bind_int(stmt, 2, record.key) != SQLITE_OK)
{
// Handle Error
}
if (sqlite3_step(statement) != SQLITE_DONE)
{
// Handle Error
}
And your Parametrized Code is ready.
You want
update field set name = ?, type = ?, state = ? where id = 5

Resources