How to use FMResultSet Group By in FMDB iOS? - ios

I want to get grouped data from a table in SQLite. For example, the table is like below:
NSString *querySQL=[[NSString alloc]initWithFormat:#"select * from %# where company like '%#%#' and sepll||first_spell||phone||name like '%#%#%#' limit %d offset %d",TABLE_NAME,company,#"%",#"%",py,#"%",pageSize,(page-1)*pageSize];
FMResultSet *rs = [[dbManager getDatabase] executeQuery:querySQL];
My question is,after executeQuery,how can I group by id ascending about rs again?
Any help is appreciated.

You should use "Group By" clause. GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
NSString *query = [NSString stringWithString:#"SELECT Row_Name1, Row_Name2 FROM Table_Name where Row_Name1 like '%%?%%' or Row_Name2 like '%%?%%' group by Row_Name1, Row_Name2 order by Row_YouWantToGroup"];
FMResultSet *rs = [theDatabase executeQuery:query];

Related

FMDB query find no result in iOS

NSString *query = #"select * from 'topic' where 'group' = ? order by lastUpdatedAtFloat desc";
FMResultSet * rs = [db executeQuery:query, groupUuid];
while ([rs next]) {
NSLog(#"show");
}
This is the query that I used, but no result is found while I am sure my database tables have data inside.
I know that FMDB query has quite some questions similar to my case, but I have not seen any reported correct demo or document for the best practice to choose which query method in the following to use for different scenarios.
- (FMResultSet *)executeQuery:(NSString *)sql;
- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments;
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
Can anyone point me a way out?

Escape special characters in FMDB iOS query

I wrote a query with arguments in FMDB using ? mark symbol.I want to get details of users who has any of info in the list(hope i can give different info separated by commas in "in" statement in sql). Since my arguments having special symbols, It is throwing error. How to escape there special symbols. I tried different methods but none worked yet
My code is like:
FMResultSet *results = [db executeQuery:#"select details from user where info in(?)",infoList];
while([results next])
{...}
Info is a string combined by different string seperated by commas.For example:
'C-note','Cuban missile crisis, the','cubbyhole','I Love Lucy','I'm a Celebrity ... Get me Out of Here!','Iacocca, Lee','-iana','Ivy League, the'
Thanks in advance
You can't use a single ? with an in clause unless you only bind a single value. It doesn't work for a list of values.
Since infoList is an array of string values, one option is to add a ? for each value in the list.
NSMutableString *query = [NSMutableString stringWithString:#"select details from user where info in ("];
for (NSInteger i = 0; i < infoList.count; i++) {
if (i) {
[query appendString:#","];
}
[query appendString:#"?"];
}
[query appendString:#")"];
FMResultSet *results = [db executeQuery:query withArgumentsInArray:infoList];

Query filtering based on dates using FMDB?

How do I query games that are after a "visible" date?
The dateformat is set:
FMDatabase *db = self.database;
if([self.database open]){
[db beginTransaction];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-dd-MM'T'HH:mm:ss'Z'"];
[db setDateFormat:formatter];
...
}
The table is created the following way:
[db executeUpdate:#"CREATE TABLE IF NOT EXISTS game (gameId Varchar(36) NOT NULL PRIMARY KEY,name TEXT,visibleFrom TEXT)"];
The query is executed the following way:
FMResultSet *results = [db executeQuery:#"SELECT * FROM game WHERE game.visibleFrom >= ?,[NSDate date]];
This returns nothing. When I use select * from game then i get all the games. But I need the filtered result. Thanks in advance.
Take a look at the SQLite syntax for querying dates: sqlite select with condition on date
You might need something like '#" ... where date > date(?)", formattedDate', where formattedDate is formatted like '1980-12-31'

SQLITE (fmdb) select where x is null not working

I'm using FMDB on iOS, attempting to query a table with a statement such as,
select * from test where foo isNull
In the sqlite C API, this ends up binding to null using this API,
int sqlite3_bind_null(sqlite3_stmt*, int);
This isn't working. The select invoked through fmdb which seems to be correctly binding the column to null is not finding matching records.
If in the sqlite3 command line session I do the following command, it works, but not through the sqlite C API via FMDB.
select * from test where foo isNull;
Here's fmdb code which reproduces the problem. It looks like fmdb is doing the proper steps invoking sqlite3_bind_null.
NSString *stmt = #"select * from test where shipToCode=:foo";
NSDictionary *dict = #{#"foo" : [NSNull null]};
FMResultSet *rs = [db executeQuery:stmt withParameterDictionary:dict];
int count = 0;
while ([rs next]) {
count++;
}
NSLog(#"Count %d", count);
NULL cannot be compared with the = operator; it is not equal with any value, even itself.
To compare with NULL, you have to use the IS NULL operator:
stmt = #"select * from test where shipToCode is null";
Try the following and check if there are any changes:
NSString *query = #"SELECT * FROM test WHERE shipToCode is NULL";
FMResultSet *rs = [db executeQuery:query];
int count = 0;
while ([rs next]) {
count++;
}
NSLog(#"Count %d", count);

Problem with FMDB and insert value in the "executeQuery:" from a searchString

While building a Search for my app i ran into a problem whilst using the FMDB SQLite Wrapper (https://github.com/ccgus/fmdb).
When I search my database with this SQL Command, everything is fine. 13 objects are returned and I can use them.
FMResultSet *rs = [db executeQuery:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE '%Daimler%'"];
But when i try to insert the searchQuery from the User Input like this:
FMResultSet *rs = [db executeQuery:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE (?)", theSearchQuery];
... the value is dont be inserted into SQL Command. And I dont get any returned objects from the DB. even if the String (theSearchQuery) is the same written in the first example.
Additionaly I post a part from the documentation of FMDB for your convinience. :)
Data Sanitization
When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax:
INSERT INTO myTable VALUES (?, ?, ?)
The ? character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an NSArray or a va_list), which are properly escaped for you.
Thus, you SHOULD NOT do this (or anything like this):
[db executeUpdate:[NSString stringWithFormat:#"INSERT INTO myTable VALUES (%#)", #"this has \" lots of ' bizarre \" quotes '"]];
Instead, you SHOULD do:
[db executeUpdate:#"INSERT INTO myTable VALUES (?)", #"this has \" lots of ' bizarre \" quotes '"];
All arguments provided to the -executeUpdate: method (or any of the variants that accept a va_list as a parameter) must be objects. The following will not work (and will result in a crash):
[db executeUpdate:#"INSERT INTO myTable VALUES (?)", 42];
The proper way to insert a number is to box it in an NSNumber object:
[db executeUpdate:#"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];
Alternatively, you can use the -execute*WithFormat: variant to use NSString-style substitution:
[db executeUpdateWithFormat:#"INSERT INTO myTable VALUES (%d)", 42];
Internally, the -execute*WithFormat: methods are properly boxing things for you. The following percent modifiers are recognized: %#, %c, %s, %d, %D, %i, %u, %U, %hi, %hu, %qi, %qu, %f, %g, %ld, %lu, %lld, and %llu. Using a modifier other than those will have unpredictable results. If, for some reason, you need the % character to appear in your SQL statement, you should use %%.
NSString *search_text = [NSString stringWithFormat:#"%%%#%%", theSearchQuery];
FMResultSet *rs = [db executeQuery:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE ?", search_text];
I would highly recommend to avoid creating queries with stringWithFormat:! There is a good reason why FMDB tries to force you to use their data sanitization. However, since FMDB is boxing your input, surrounding parenthesis in the following code are not needed and may cause your problem.
[db executeQuery:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE (?)", theSearchQuery];
Simple add arguments without any parenthisis because you never know how FMDB boxes your argument internally.
[db executeQuery:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE ?", theSearchQuery];
If this still doesn't work try to use the suggested executeQueryWithFormat: method of FMDB:
[db executeQueryWithFormat:#"SELECT * FROM ZARTICLE WHERE ZTITLEDE LIKE %#", theSearchQuery];

Resources