Saving entire NSArray in SQLite - ios

I want to saving entire array into SQLite. I am getting an array having many other arrays in that.
Is it possible ? If so please let tell me.
I have tried this - But "ERROR TO SAVE DATA"
NSArray *array = [dict objectForKey:#"events_data"];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO CONTACTS (event_array) VALUES (\"%#\")", array];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DATA SAVED TO DB");
} else {
NSLog(#"ERROR TO SAVE DATA");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
If it is possible please tell me how to retrieve it also.

You need not use sqlite directly in iOS. Indeed, you should wrap the persistent object in an NSManagedObject. To retrieve the object, simply create an NSFetchRequest, set its entity, and have the context execute it, which will return a standard NSArray of NSManagedObjects, which you can iterate over. Hope this helped, please leave a comment if you have further issues.

Related

does it possible to save Db file with application and not by adding in from itunes

I want the application which work online as well as offline example WhatsApp. For that i have to sync data from web service then store it in sqlite db file.
And I want that whoever installs this application would have a slot for automatic saving data in database file. Do I have to add db file from iTunes?
I don't want to use core data concept.
Is it possible it will be there in with application?
Like in Android there is something called cache memory where db file is stored so there is any sort of provision for it in ios?
+(int)insert_In_AdverImage:(NSString *)strid ImageName:(NSString *)strimg Isshow:(NSString *)strshow LastUpdateId:(NSString *)date isdelete:(NSString *)isdelete Sortorder:(int)sortOrder{
sqlite3 *database;
int retValue = 0;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *tempSQL = [[NSString alloc] initWithFormat:#"INSERT INTO ADVERIMAGE(advId ,advimg ,isshow ,LastUpdateId ,IsDelete ,SortorderId ) VALUES ('%#', '%#', '%#', '%#', '%#', '%d')", strid, strimg, strshow, date, isdelete, sortOrder];
const char *sqlStatement = [tempSQL cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *compiledStatement;
sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL);
sqlite3_step(compiledStatement);
retValue = (int)sqlite3_last_insert_rowid(database);
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return retValue;
}
works well. But still the db file in app bundle is empty.i got it that whenever we insert something it will be inserted in document and if we have to see the inserted data we have to get it from document
Thanks in advance
Any Help would be appreciated.
Yes. Possible.
You can store SQlite DB in your applications's Document Directory. You need to write your own Query to Open DB, Insert Data, Retrieve Data from DB.
Check out following tutorial for your requirement : http://www.appcoda.com/sqlite-database-ios-app-tutorial/
Hope it helps.
Following function is used to Insert :
NSArray *docsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [docsDirectory objectAtIndex:0];
NSString *databasePath = [docPath stringByAppendingPathComponent:#"Database.sqlite"];
sqlite3 *dbHandler;
const char *dbPath = [databasePath UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_open(dbPath, &dbHandler) == SQLITE_OK)
{
if (sqlite3_prepare_v2(dbHandler, [queryString UTF8String], -1, &sqlStmt, NULL) == SQLITE_OK)
{
if (sqlite3_step(sqlStmt) == SQLITE_DONE)
{
NSLog(#"Data Inserted");
}
else
{
NSLog(#"Not inserted");
}
}
else
{
NSLog(#"Failed to Insert data -InsertDataFunc");
}
sqlite3_close(dbHandler);
}

sqlite DB is shows SQLITE_BUSY after the getting sqlite3_last_insert_rowid() objective c

I am trying to insert a member in sqlite DB member table. After inserting values if I take sqlite3_last_insert_rowid() I can't insert another member. the statement shows SQLITE_BUSY.Here is my code. Please anybody help.
-(NSInteger) saveMember:(TMMember *)member {
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"insert into members (memberName, memberAmount,shareFlag) values(\"%#\", \"%f\",%d)",member.memberName,member.amount,[[NSNumber numberWithBool:member.shareFlag]intValue]];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE)
{
NSInteger lastRowId = sqlite3_last_insert_rowid(database);
member.memberId = lastRowId;
NSLog(#"inserted member id = %ld",lastRowId);
NSLog(#"member is added");
}
sqlite3_finalize(statement);
statement = nil;
}
sqlite3_reset(statement);
sqlite3_close(database);
return 0;
}
This error is getting when sqlite already processing another statement, and you are trying to execute another one. So the db is locked until you finalise the statement.
For more info. Read: SQLite Exception: SQLite Busy

How to Set Sqllite Result Set to insert Only Distinct Value in iOS?

i am newbie in iOS and also newbie in sqllite database so please help me for my Question. I want to Insert Only Distinct Value in sqllite Table, like as Here i Insert Value in to My Table
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_myDatabase) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO ALLREADTABLE (PostId, PostTitle, ImageLink, ShortDescription,Category,PostDate) VALUES (\"%#\", \"%#\", \"%#\", \"%#\",\"%#\",\"%#\")",
post_id, cell.headLabel.text, image,self.shortDiscription,cell.categoryLabel.text,cell.timeLabel.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_myDatabase, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSString *string=[NSString stringWithFormat:#"Value Added %# %# %# %# %# %# ",post_id, cell.headLabel.text, image,self.shortDiscription,cell.categoryLabel.text,cell.timeLabel.text];
NSLog(#"String %#",string);
} else
{
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(_myDatabase);
}
Now i want when i insert same value into table then i want old value are deleted and new value are inserted in to my table.How it is Possible Please Give me Solution for it.

Saving NSArray in SQLite and retrieving it

In my iPHone app I am saving an NSArray in sqlite like this.
-(void)saveData
NSData *dataFromArray = [NSKeyedArchiver archivedDataWithRootObject:MyArray];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO ARRAY(PROFILE) VALUES (\"%#\")",dataFromArray];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Saved Succesfully");
}
else {
// NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(contactDB));
NSLog(#"Not saved %d",sqlite3_finalize(statement));
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
Data is saved successfully.
Now I tried to fetch the saved data like this-
-(void)fetchData{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM ARRAY"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *MYstring = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSData* data = [MYstring dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"data---%#",data);
NSArray *myArrayFromDB = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
I am getting print value for "MYstring" like this
<62706c69 73743030 d4000100 02000300 04000500 0806cb06 cc542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572d100 06000754 726f6f74 8001af11 022a0009 000a0017 00180019 001a0080 00810082 00830084 00850086 00870088 0089008a 008b008c 008d008e 008f0090 00910092 00930094 00950096 00970098 0099009a 009b009c 009d009e 009f00a0 00a100a2 00a300a4 00a500a6 00a700a8 00a900aa 00ab00ac 00ad00ae 00af00b0 00b100b5 00bd00c0 00c300c6 00c900cc 00cf00d2 00d500d8 00db00de 00e100e4 00e700ea 00ed00f0 00fd0105 0108010b 010e0111 01140117 011a011d 01200122 0127012a 012d0130 01330136 0139013c 013f0142 01450148 014b014e 01510154 0159015e 01610164 0169016f 018101a1 01a201a3 01a401a5 01a601a7 01a801a9 01aa01ab 01ac01ad 01ae01af 01b201b5 01b801bb 01be01c1 01c401c7 01ca01cd 01d001d3 01d601d9 01f901fa 01fb01fc>
But when I try to create NSArray from data using NSKeyedUnarchiver - the app got crashed showing this error
-[__NSCFData objectForKey:]: unrecognized selector sent to instance
Where I am making the mistake ?
Please help me to retrieve the saved array, Thanks in advance.
Why do you use NSData? Once the string received, write below line
NSArray *myArrayFromDB = [MYstring componentsSeparatedByString:#","];
Try this if it is working. Let me know if not and I find another solution
NSData *dataFromArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
This creates an XML representation of myArray and places it in dataFromArray. Something like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="1.0">
<array>
<string>It is a tale told by an idiot,</string>
<string>Full of sound and fury, signifying nothing.</string>
</array>
</plist>
The XML is converted to UTF8 format and stored in the NSData object.
When you do:
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO ARRAY(PROFILE) VALUES (\"%#\")",dataFromArray];
the stringWithFormat operation interprets the format string. When it sees %#, it thinks "I must take the next object reference from the parameter list, apply the description method to it, and place that into the string."
The description method of NSData takes the <?xml version... data and converts it into displayable hex (since description is intended to be used purely for debugging, never "real" code). The displayable hex is formatted in groups of 8 characters, separated by blanks and enclosed in "<>" characters. By now the data is hopelessly garbled, and you haven't even inserted it into the DB yet.

Delete all records from table in sqlite database

I know this is very frequently asked question and i tried everything that i found here. But problem is still there.
Now the problem is i am trying to delete all records from 3 tables with following code but they are not being deleted
const char *dbpath = [dbPathString UTF8String];
sqlite3 *sqliteDB;
if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
//Delete all records from attempts
sqlite3_stmt *statement;
NSString *deleteSQL = [NSString stringWithFormat: #"DELETE FROM table1"];
const char *delete_stmt = [deleteSQL UTF8String];
sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);
sqlite3_finalize(statement);
sqlite3_close(sqliteDB);
}
if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
//Delete all records from attempts
sqlite3_stmt *statement;
NSString *deleteSQL = [NSString stringWithFormat: #"DELETE FROM table2"];
const char *delete_stmt = [deleteSQL UTF8String];
sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);
sqlite3_finalize(statement);
sqlite3_close(sqliteDB);
}
if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
//Delete all records from attempts
sqlite3_stmt *statement;
NSString *deleteSQL = [NSString stringWithFormat: #"DELETE FROM table"];
const char *delete_stmt = [deleteSQL UTF8String];
sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);
sqlite3_finalize(statement);
sqlite3_close(sqliteDB);
}
I have tried with if conditions like
if (sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL) == SQLITE_OK) {
NSLog("All records deleted");
}
And this if condition get executed and i do have statement in console log.
I am using Xcode 5.0.
Please help me. Thanx in advance
sqlite3_prepare_v2 just prepares the statement.
To actually execute it, you must also call sqlite3_step.
Dear friend this is little bit complex coding try to use external class for easy coding
this link will help you
How to insert update delete in database operation and also save database in document directory
for delete record you can use
NSString *strDelete = [Database executeScalarQuery:#"DELETE FROM table1"];
Happy Coding!!!

Resources