Related
I have a sqlite db and i want to insert row in it . I used this code for inserting rows and make a query.
-(void)InsertRecords{
querySQL1 = #"select category from notes where id=5";
const char * query_stmt = [querySQL1 UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO notes (id, title, content,dataAdd,category) VALUES (\"%#\", \"%#\", \"%#\" ,\"%#\",\"%#\")",
#"5",
#"georgiana",
#"20",
#"12.09.2019",
#"public"];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_stmt *updateStmt = nil;
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if(sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK){
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"data inserted");
}
else{
NSLog(#"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB));
}
}
else
NSLog(#"Error while creating update statement. '%s'", sqlite3_errmsg(contactDB));
querySQL1 = #"select id from notes where category LIKE 'public'";
query_stmt = [querySQL1 UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
NSString *idNr=#"";
while (sqlite3_step(statement) == SQLITE_ROW)
{
idNr =[NSString stringWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
}
NSLog(#"%#",idNr);
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
Everything is ok, but when I open the app again, I don't find any value for idNr.
Any useful help will be appreciated.
The NSString allocation is wrong statement, There is no need to alloc NSString object here.
The method stringWithUTF8String: is class method. This will do the allocation for NSString.
Replace your code like below:
NSString *idNr = #"";
while (sqlite3_step(statement) == SQLITE_ROW) {
idNr = [NSString stringWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
}
I've used the following method in my app,
-(int) getMax:(NSString *)subItemName second :(int) tableID
{
int count1=0;
sqlite3_stmt *statement;
NSString *query = [NSString stringWithFormat:#"Select MAX(NoOfItems) from billTable where SubItemName='%#' AND TableID='%d'",subItemName,tableID];
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil)== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
count1 = [[NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)]intValue];
}
sqlite3_step (statement);
}
return count1;
}
As you can see that the my query will return the no of rows (an integer), suppose if my query returns a NULL value(if there is no such exists for the where clause condition in my database it returns NULL value. How to check it returns NULL after the query has been executed?
You can call sqlite3_column_type() to find out what type a column value has:
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil)== SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
if (sqlite3_column_type(statement, 0) == SQLITE_NULL)
count1 = -1; // or whatever
else
count1 = sqlite3_column_int(statement, 0);
}
sqlite3_finalize(statement);
}
I have a "messages table" , and i want only to retrieve the "user ID" with his last message.
I tried to add "2 sql statements" inside each other , But it keeps on looping without stopping,
sqlite3_stmt *statement;
NSMutableArray * messages = [[NSMutableArray alloc]init];
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_chatDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT DISTINCT FROMID , USERNAME from CHATCOMPLETE"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_chatDB,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
int userID = [[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)] integerValue];
NSString *querySQL2 = [NSString stringWithFormat:
#"SELECT MESSAGE , USERNAME from CHATCOMPLETE where FROMID=\"%d\"",userID];
const char *query_stmt2 = [querySQL2 UTF8String];
if (sqlite3_prepare_v2(_chatDB,
query_stmt2, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"LAST MESSAGE %#",[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)]);
sqlite3_reset(statement);
}
}
}
sqlite3_reset(statement);
}
}
return messages;
UPDATE:
This is the insert message
-(void)saveData:(NSString *)message toID:(int)toID fromID:(int)fromID isRead:(BOOL)read date:(NSDate *)date messageID:(int)messageID userName:(NSString*)userName
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_chatDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO CHATCOMPLETE (MESSAGE, TOID, FROMID, READ, date, MESSAGEID, USERNAME) VALUES (\"%#\", \"%d\", \"%d\", \"%c\", \"%#\", \"%d\", \"%#\")", message, toID, fromID, read, date,messageID,userName];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_chatDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DONE");
/* status.text = #"Contact added";
name.text = #"";
address.text = #"";
phone.text = #"";*/
} else {
// status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(_chatDB);
}
}
This is the query to get the last message with a given fromID:
SELECT * FROM chatting WHERE fromID=9999 ORDER BY id DESC LIMIT 1
In SQLite 3.7.11 or later, the following query will return the message with the largest date for each sender:
SELECT *, MAX(date)
FROM ChatComplete
GROUP BY FromID
There are a few issues:
You have only one sqlite3_stmt variable for your two nested queries. You want a separate sqlite3_stmt for each.
You are calling sqlite3_reset. That is only used when binding new values to ? placeholders in your prepared statement, which is not applicable here. Worse, you're calling it inside your loop.
Unrelated to the problem at hand, but for each prepared statement, don't forget to call sqlite3_finalize when done looping through the results, in order to release the memory used when preparing the statements.
Thus, you might want something like:
sqlite3_stmt *userStatement;
sqlite3_stmt *messageStatement;
int rc; // the return code
NSMutableArray * messages = [[NSMutableArray alloc]init];
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_chatDB) == SQLITE_OK)
{
const char *query_stmt = "SELECT DISTINCT FROMID , USERNAME from CHATCOMPLETE";
if (sqlite3_prepare_v2(_chatDB, query_stmt, -1, &userStatement, NULL) != SQLITE_OK)
{
NSLog(#"%s: prepare userStatement failed: %s", __PRETTY_FUNCTION__, sqlite3_errmsg(_chatDB));
}
else
{
while ((rc = sqlite3_step(userStatement)) == SQLITE_ROW)
{
int userID = [[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)] integerValue];
const char *query_stmt2 = "SELECT MESSAGE , USERNAME from CHATCOMPLETE where FROMID=? ORDER BY timestamp DESC LIMIT 1"; // change the `ORDER BY` to use whatever field you want to sort by
if (sqlite3_prepare_v2(_chatDB, query_stmt2, -1, &messageStatement, NULL) != SQLITE_OK)
{
NSLog(#"%s: prepare messageStatement failed: %s", __PRETTY_FUNCTION__, sqlite3_errmsg(_chatDB));
}
else
{
if (sqlite3_bind_int(messageStatement, 1, userID) != SQLITE_OK)
{
NSLog(#"%s: bind userID %d failed: %s", __PRETTY_FUNCTION__, userID, sqlite3_errmsg(_chatDB));
}
while ((rc = sqlite3_step(messageStatement)) == SQLITE_ROW)
{
NSLog(#"LAST MESSAGE %#",[[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)]);
}
if (rc != SQLITE_DONE)
{
NSLog(#"%s: step messageStatement failed: %s", __PRETTY_FUNCTION__, sqlite3_errmsg(_chatDB));
}
sqlite3_finalize(messageStatement);
}
}
if (rc != SQLITE_DONE)
{
NSLog(#"%s: step userStatement failed: %s", __PRETTY_FUNCTION__, sqlite3_errmsg(_chatDB));
}
sqlite3_finalize(userStatement);
}
}
else
{
NSLog(#"%s: open %# failed", __PRETTY_FUNCTION__, _databasePath);
}
return messages;
Note, this code sample, in addition to my three points above, also:
Log errors using sqlite3_errmsg if sqlite3_prepare_v2 fails.
Added check on return codes from sqlite3_step, too, again logging sqlite3_errmsg if it fails.
Added log if sqlite3_open failed.
Use sqlite3_bind_int() rather building SQL using stringWithFormat. In this case, because userID is numeric, this isn't critical, but if ever using string values in your WHERE clauses, using the sqlite3_bind_text() function becomes critical, so I just wanted to show the pattern.
For example, look at your save routine and try saving a message that happens to have double quotation mark in it (e.g. I spoke with Bob and he says "hello" to you.). Your stringWithFormat construct will fail. If you use sqlite3_bind_text, it will solve that problem.
BTW, as you can see, when you add all of the proper validation of results, binding of values, etc., the code becomes a bit unwieldy. You might consider using FMDB, which greatly simplifies your SQLite Objective-C code.
In the code below, the commented-out code works.
But using the saveData method of the DBMgr Class results in "Failded to add contact".
I want to see "Contact added" instead.
-(void) saveData{
NSString *insSQL = [NSString stringWithFormat:#"INSERT INTO CONTACTS (name,address,phone) VALUES (\"%#\",\"%#\",\"%#\")",name.text,address.text,phone.text];
DBMgr *dbmgr = [DBMgr alloc];
if([dbmgr saveData:insSQL]== 0){
status.text = #"Contact added";
}else if([dbmgr saveData:insSQL]== 1){
status.text=#"Failded to add contact";
}
/*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 (\"%#\",\"%#\",\"%#\")",name.text,address.text,phone.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 = #"";
phone.text = #"";
}else{
status.text=#"Failded to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}*/
}
-(NSInteger) saveData:(NSString *) querySQL{
NSInteger result;
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = querySQL;
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE)
{
result = 0;
}else{
result = 1;
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
return result;
}
You should check the result codes of all of your SQLite calls, and if they fail, log the error:
- (NSInteger) saveData:(NSString *) querySQL{
NSInteger result = 1;
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = querySQL;
const char *insert_stmt = [insertSQL UTF8String];
if (sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) != SQLITE_OK)
NSLog(#"%s: prepare failed: %s", __FUNCTION__, sqlite3_errmsg(contactDB));
else
{
if(sqlite3_step(statement) == SQLITE_DONE)
{
result = 0;
}else{
NSLog(#"%s: step failed: %s", __FUNCTION__, sqlite3_errmsg(contactDB));
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
} else {
NSLog(#"%s: open failed", __FUNCTION__);
}
return result;
}
Unless you look at sqlite3_errmsg, you're just guessing. And check sqlite3_prepare_v2 return code, too, like I did above, (as that will more likely be the initial indication of a problem).
Two other, unrelated, observations:
The DBMgr should be initialized, e.g.:
DBMgr *dbmgr = [[DBMgr alloc] init];
You are building your INSERT statement using stringWithFormat. That's very dangerous, you should use ? placeholders in your SQL:
const char *insSQL = "INSERT INTO CONTACTS (name,address,phone) VALUES (?, ?, ?)";
sqlite3_prepare_v2(contactDB, insSQL, -1, &statement, NULL);
Then, after preparing that statement, you should then use the sqlite3_bind_text function to assign your values to those three placeholders, e.g.
sqlite3_bind_text(statement, 1, [name.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, [address.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, [phone.text UTF8String], -1, SQLITE_TRANSIENT);
By the way, if you wanted to specify NULL, you'd call sqlite3_bind_null instead of sqlite3_bind_text.
Obviously, check the return code from each of those to make sure you returned SQLITE_OK for each, again, logging sqlite3_errmsg if it failed.
I appreciate that this change is going to require some refactoring of your code, but it's important to use sqlite3_bind_text to avoid SQL injection attacks and errors that will result if the user typed in a value that included quotation marks.
By the way, if you're looking at the above and realizing that it takes a lot of code to do this properly, you might want to consider using FMDB which can significantly simplify your life.
i have a view Controller called as VegQuantity which does totalcost=(quantity*cost of the dish) and inserts the itemname,quantity,totalcost into a table called as FINALORDER with database name FinalOrder
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &FinalOrder) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO FINALORDER (itemname, quantity, totalcost) VALUES (\"%#\", \"%#\", \"%#\")", itemName.text, input.text, output.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(FinalOrder, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
// status.text = #"Contact added";
// name.text = #"";
// address.text = #"";
// phone.text = #"";
NSLog(#"added");
} else {
NSLog(#"Couldnt add");
}
sqlite3_finalize(statement);
sqlite3_close(FinalOrder);
}
Final View Controller viewdidload method
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &FinalOrder) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM FINALORDER"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(FinalOrder, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *itemname = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
item.text = itemname;
NSString *qua = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
quantity.text = qua;
NSString *total = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
totalcost.text=total;
}
sqlite3_finalize(statement);
}
sqlite3_close(FinalOrder);
}
But i keep getting this error called expected expression before FinalOrder,and is it correct for me to write this code inside viewdidload? i dont have any button in Final view controller i have a button called order in a view controller called as Restaurant which actually shows me Final view controller..am i supposed to search for the db file again in the Final viewcontroller and i am sorry question seems kind of vague but in brief i just want to know how to retrieve and display the data which i have inserted in VegQuantity view controller into the final view controller thanks
I believe that the problem must rest in the definition of FinalOrder which, on the basis of the error message, looks like has been defined as a class, not as a sqlite3 * variable. Given that the scope of your usage of the database is limited to these two methods, I'd suggest defining a sqlite3 * within that scope, and use that, such as:
- (void)saveRecord
{
sqlite3 *database;
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
[self purgeTable:database];
NSString *insertSQL = #"INSERT INTO FINALORDER (itemname, quantity, totalcost) VALUES (?, ?, ?)";
if (sqlite3_prepare_v2(database, [insertSQL UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [itemName.text UTF8String], -1, NULL);
sqlite3_bind_int(statement, 2, [input.text intValue]);
sqlite3_bind_double(statement, 3, [output.text doubleValue]);
if (sqlite3_step(statement) == SQLITE_DONE)
{
// status.text = #"Contact added";
// name.text = #"";
// address.text = #"";
// phone.text = #"";
NSLog(#"added");
} else {
NSLog(#"%s Couldn't add; errmsg='%s'", __FUNCTION__, sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
} else {
NSLog(#"%s Couldn't prepare; errmsg='%s'", __FUNCTION__, sqlite3_errmsg(database));
}
sqlite3_close(database);
}
}
Note, in addition to using a sqlite3 * variable for the database, to make this a little more robust:
I have replaced the stringWithFormat statement that built the SQL insert statement with an INSERT statement that uses the ? placeholders and then use sqlite3_bind_text to bind values to that statement. This way, if someone entered a value that included a quotation mark, the insert statement will still work (your original implementation would have crashed and/or was susceptible to a SQL injection attack).
I have also added the sqlite3_errmsg statements so if something goes wrong, I know what the problem was.
Rather than treating these three fields as text fields, I'm assuming your table is defined as CREATE TABLE IF NOT EXISTS FINALORDER (itemname TEXT, quantity INT, totalcost REAL); and therefore use text, int, and double bind statements.
This, incidentally, invokes a purgeTable method, so if you run it twice, it will remove the old record in there:
- (void)purgeTable:(sqlite3 *)database
{
if (sqlite3_exec(database, "DELETE FROM FINALORDER;", NULL, NULL, NULL) != SQLITE_OK)
NSLog(#"%s Couldn't purge table %s", __FUNCTION__, sqlite3_errmsg(database));
}
Anyway, you can then read this data via:
- (void)loadRecord
{
sqlite3 *database;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = #"SELECT * FROM FINALORDER";
if (sqlite3_prepare_v2(database, [querySQL UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *itemname = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
item.text = itemname;
//[itemname release]; // if not ARC, uncomment this line
int qua = sqlite3_column_int(statement, 1);
quantity.text = [NSString stringWithFormat:#"%1d", qua];
double total = sqlite3_column_double(statement, 2);
totalcost.text = [NSString stringWithFormat:#"%1.2f", total];
}
sqlite3_finalize(statement);
} else {
NSLog(#"%s Couldn't prepare; errmsg='%s'", __FUNCTION__, sqlite3_errmsg(database));
}
sqlite3_close(database);
}
}
Note,
I've added a sqlite3_errmsg log statement if the sqlite3_prepare fails, and I've retired the stringWithFormat (because you weren't formatting anything).
Given that quantity was INT and total was REAL, I'm retrieving the values using the appropriate variation of sqlite3_column_text, sqlite3_column_int, or sqlite3_column_double, as appropriate.
I infer that you're not using ARC and therefore, the [NSString alloc] must have an associated release or autorelease.
Finally, in our chat, you said that you received an error message (presumably an "Undefined Symbols" message) that said:
OBJC_CLASS_$"_FinalOrder"
This means that you are trying to use an object class of FinalOrder, but you haven't defined that class anywhere. Take a look at which .o files it's reporting this error for and look at the corresponding .m file, and look for your use of the FinalOrder class there. You clearly have a FinalOrder class interface defined somewhere, but never defined the class implementation, or, if you have one, for some reason it's not included in your target's "Compile Sources" listing, so double check it's here:
Finally, by the way, make sure your database is in the Documents folder, not trying to open a copy of the database in your project's bundle (because that's read only). If you have a copy of the database in your bundle, just check to see if you already have it in you Documents folder, and if not, copy it from the bundle to the Documents folder.