FMDB query find no result in iOS - 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?

Related

How to use FMResultSet Group By in FMDB 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];

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

Bind parameter in FROM clause in SQLite

Is it possible to bind a parameter in the FROM clause of a query to SQLite? How?
If not, why? Any alternatives?
Here is what I want to do in my iOS application:
- (BOOL)existsColumn:(NSString *)column inTable:(NSString *)table ofDatabase:(FMDatabase *)database {
NSString *query = #"SELECT ? FROM ? LIMIT 0";
NSArray *queryParameters = #[column, table];
return (BOOL)[database executeQuery:query withArgumentsInArray:queryParameters];
}
Here is the error message I get:
near "?": syntax error
I understand that there are other ways to check if a column exists. I am specifically curious why I can't bind a parameter in the FROM clause (only binding a parameter in the SELECT clause above works so it must be an issue with the FROM clause).
The ? should only be used for binding actual values into the query such in the VALUES section of an INSERT or values in a WHERE clause.
For dynamically building the column and table names you should simply use a string format to build the query string before sending it to FMDB.
- (BOOL)existsColumn:(NSString *)column inTable:(NSString *)table ofDatabase:(FMDatabase *)database {
NSString *query = [NSString stringWithFormat:#"SELECT %# FROM %# LIMIT 0", column, table];
return (BOOL)[database executeQuery:query];
}
Please note that you should not use the string format in place of using ? and proper value binding for actual values (which you don't have in this case).

Multiple Queries not Running in FMDB

I'm using FMDB to create a SQLite database on iPhone. I have a initial.sql that is of the form
CREATE TABLE Abc ... ;
CREATE TABLE Def ... ;
I load this by loading the file into an NSString and running it
NSString * str = // string from file initial.sql
[db executeUpdate: str];
This succeeds but later on I get a failure:
no such table: Def
It's clear that the second statement is not being called. How can I do this so that all of the queries will be called?
According to the SQLite documentation:
"The routines sqlite3_prepare_v2(), sqlite3_prepare(), sqlite3_prepare16(), sqlite3_prepare16_v2(), sqlite3_exec(), and sqlite3_get_table() accept an SQL statement list (sql-stmt-list) which is a semicolon-separated list of statements."
So, this should all work.
I got bitten by this one too; it took me an entire morning of stepping through FMDatabase and reading the sqlite3 API documentation to find it. I am still not entirely sure about the root cause of the issue, but according to this bug in PHP, it is necessary to call sqlite3_exec instead of preparing the statement with sqlite3_prepare_v2 and then calling sqlite3_step.
The documentation does not seem to suggest that this behaviour would happen, hence our confusion, and I would love for someone with more experience with sqlite to come forward with some hypotheses.
I solved this by developing a method to execute a batch of queries. Please find the code below. If you prefer, you could rewrite this into a category instead of just adding it to FMDatabase.h, your call.
Add this to the FMDatabase interface in FMDatabase.h:
- (BOOL)executeBatch:(NSString*)sql error:(NSError**)error;
Add this to the FMDatabase implementation in FMDatabase.m:
- (BOOL)executeBatch:(NSString *)sql error:(NSError**)error
{
char* errorOutput;
int responseCode = sqlite3_exec(db, [sql UTF8String], NULL, NULL, &errorOutput);
if (errorOutput != nil)
{
*error = [NSError errorWithDomain:[NSString stringWithUTF8String:errorOutput]
code:responseCode
userInfo:nil];
return false;
}
return true;
}
Please note that there are many features missing from executeBatch which make it unsuitable for a lot of purposes. Specifically, it doesn't check to see if the database is locked, it doesn't make sure FMDatabase itself isn't locked, it doesn't support statement caching.
If you need that, the above is a good starting point to code it yourself. Happy hacking!
FMDB v2.3 now has a native wrapper for sqlite3_exec called executeStatements:
BOOL success;
NSString *sql = #"create table bulktest1 (id integer primary key autoincrement, x text);"
"create table bulktest2 (id integer primary key autoincrement, y text);"
"create table bulktest3 (id integer primary key autoincrement, z text);"
"insert into bulktest1 (x) values ('XXX');"
"insert into bulktest2 (y) values ('YYY');"
"insert into bulktest3 (z) values ('ZZZ');";
success = [db executeStatements:sql];
It also has a variant that employs the sqlite3_exec callback, implemented as a block:
sql = #"select count(*) as count from bulktest1;"
"select count(*) as count from bulktest2;"
"select count(*) as count from bulktest3;";
success = [db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
NSInteger count = [dictionary[#"count"] integerValue];
NSLog(#"Count = %d", count);
return 0; // if you return 0, it continues execution; return non-zero, it stops execution
}];
Split Batch Statement
Add in .h file:
#import "FMSQLStatementSplitter.h"
#import "FMDatabaseQueue.h"
FMSQLStatementSplitter can split batch sql statement into several separated statements, then [FMDatabase executeUpdate:] or other methods can be used to execute each separated statement:
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:databasePath];
NSString *batchStatement = #"insert into ftest values ('hello;');"
#"insert into ftest values ('hi;');"
#"insert into ftest values ('not h!\\\\');"
#"insert into ftest values ('definitely not h!')";
NSArray *statements = [[FMSQLStatementSplitter sharedInstance] statementsFromBatchSqlStatement:batchStatement];
[queue inDatabase:^(FMDatabase *adb) {
for (FMSplittedStatement *sqlittedStatement in statements)
{
[adb executeUpdate:sqlittedStatement.statementString];
}
}];

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