My Select query is breaking of single inverted comma in the where clause string like (select * from where Col_Name in(?),new String []{list});
and list ="'abc','tyur','iop','nj'd','sjc'jskj'";
please let me know if there is any workaround for the above-mentioned issue.
You need to escape the ' character before passing it in the query.
Replace ' with ''(two single quotes) in your string.
Here is a simple string sanitizer for sql queries.
public static String sanitizeSqlString(String text) {
return text !=null ? text.replace("\'", "\'\'")
.replace("\"", "\"\"")
.replace("`", "``")
.replace("\\", "\\\\") : text;
}
You need to sanitize each element by iterating through the list.
Related
My Problem:
I'm struggling to eliminate the compiling error on the following Room #Query statement in a Room DAO. As you can see, the SQLite query statement is joining various fields from different tables. The missing fields identified by the error are a part of the Notes class constructor identified in the List type for the method. I think I need to change the List type identified. If I'm right, I need some guidance/suggestion on how I should resolve it. Do I need to create a new Class and DAO with just those specific fields queried? Or maybe just a class since there is not table specific to these fields only. The error is:
error: The columns returned by the query does not have the fields [commentID,questionID,quoteID,termID,topicID,deleted] in com.mistywillow.researchdb.database.entities.Notes even though they are annotated as non-null or primitive. Columns returned by the query: [NoteID,SourceID,SourceType,Title,Summary]
List getNotesOnTopic(String topic);
#Query("SELECT n.NoteID, s.SourceID, s.SourceType, s.Title, c.Summary FROM Comments as c " +
"LEFT JOIN Notes as n ON n.CommentID = c.CommentID " +
"LEFT JOIN Sources as s ON n.SourceID = s.SourceID " +
"LEFT JOIN Topics as t ON n.TopicID = t.TopicID WHERE t.Topic = :topic AND n.Deleted = 0")
List<Notes> getNotesOnTopic(String topic);
What I'm trying to do:
I'm attempting to convert and existing Java desktop app with an embedded an SQLite database. The above query does work fine in that app. I only want to pass field data from these tables.
What I've tried:
I've done some googling and visited some forums for the last few days (e.g. Android Forum, Developer.Android.com) but most of the Room #Query examples are single table full field queries (e.g. "Select * From table"). Nothing I found yet (there is probably something) quite addresses how and what to do if you are joining and querying only specific fields across tables.
I think I may have fixed my issue. I just created a new class called SourceTable and designated the queried fields in the constructor. The only catch was I, according to a follow up error, was that the parameters had to match the field names.
public class SourcesTable {
private int NoteID;
private int SourceID;
private String SourceType;
private String Title;
private String Summary;
public SourcesTable(int NoteID, int SourceID, String SourceType, String Title, String Summary){
this.NoteID = NoteID;
this.SourceID = SourceID;
this.SourceType = SourceType;
this.Title = Title;
this.Summary = Summary;
}
}
and then I update my list method:
List<SourcesTable> getNotesOnTopic(String topic);
I have a rather big query that is returning data when executed outside android while returning nothing when executed within android.
I split the query in several pieces and determined that the union was ok.
I tried on a smaller set of data with the same behavior.
I've tested with different hardware and API versions.
I'm using the rawQuery method with constant values.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String, java.lang.String[])
This query was meant to replace a FULL OUTER JOIN which is not currently supported.
SELECT IFNULL(stype, gtype) AS type, IFNULL(sdate, gdate) AS date, IFNULL(sroute, groute) AS route FROM (
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM Sensor_Point AS sp LEFT JOIN GPS_Point AS gp ON gp._id IS NULL AND sp.sent=0 AND sp.route=gp.route AND sp.route=1
UNION ALL
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM GPS_Point AS gp LEFT JOIN Sensor_Point AS sp ON sp._id IS NULL AND gp.sent=0 AND sp.route=gp.route AND gp.route=1
) WHERE route=1 ORDER BY date ASC LIMIT 255
Any hints would be greatly appreciated.
Update:
Look's like the problem is finally with the query parameters, if I set it this way:
String[] args = new String[3];
args[0] = args[1] = args[2] = "1";
Cursor data dataBase.rawQuery(SELECT_POINTS, args);
It doesn't work, while it works when hardcoding values directly in the query.
Cursor data = dataBase.rawQuery(SELECT_POINTS, null);
In the Android database API, all query parameters are strings.
(This is a horrible design mistake.)
Your query corresponds to:
... AND sp.route='1'
Try to convert the parameter strings back into a number like this:
... AND sp.route = CAST(? AS INT)
or just put the number directly into the query string.
I'm working on an android app that uses sugarORM. I want to get a multiple items that match the ids in a list.
However when i call
findWithQuery(A.class, "SELECT * FROM <table> WHERE <column> in (?)", "1,2,3")
I always get an empty list(although I double checked the query with SQLite DB Browser and it worked).
Splitting this query into multiple findById seems inefficient. Any thoughts on getting WHERE IN to work using SugarORM?
After more attempts I found that there is a problem with replacing the placeholders.
Switching from:
findWithQuery(A.class, "SELECT * FROM <table> WHERE <column> in (?)", "1,2,3")
To:
findWithQuery(A.class, "SELECT * FROM <table> WHERE <column> in (1,2,3)", null)
fixes the issue.
The issue is that SQLite escapes the arguments "1,2,3" and turns it into a single value that is then used to replace the single ? placeholder in your query string. The correct way to supply multiple arguments would be to have a placeholder for every individual argument. Your original line of code would then have to change to:
findWithQuery(A.class, "SELECT * FROM <table> WHERE <column> in (?,?,?)", new String[] { "1","2","3" })
You later pointed out that the number of arguments is dynamic. This you can easily be accomplished by generating the query (the where clause in particular) at runtime based on the arguments that you want to query for.
For the most general case, it only takes a few lines of code to do so:
final String[] args = new String[] { /* ... */ };
final String query = "SELECT * FROM <table> WHERE <column> in " +
"(" + TextUtils.join(",", Collections.nCopies(args.length, "?")) + ")";
final List<A> result = A.findWithQuery(A.class, query, args);
(note that you could take a shortcut and inject the arguments directly into the query string - instead of using placeholders - but then you'll loose SQLite's built-in escaping, so I decided against that)
All that's left to do is to generate a String[] out of your arguments. A simple helper method like this should cover most scenarios:
static String[] toStringArray(Object... args) {
final String[] array = new String[args.length];
for (int i = 0; i < args.length; i++) array[i] = args[i].toString();
return array;
}
You'll probably want to add some null checks in there and potentially set up a few overloads if you plan on using primitive arrays as arguments.
Disclaimer: I typed everything straight into the browser, so no guarantees that everything works and the first try. :)
I have a very long string in the database that needs to be retrieved into a swipe view.
But,the problem is that the string comprises of set of "\n\n"
Whenever it is separated with this expression i need to put it in another slide,i mean i am using SWIPE view here..
if(tablecolumn==\\n\\n)
{
code to break it to parts
}
Is this how i should be doing it?
If i am wrong,how to break this string to different parts and enable it into SWIPE VIEW in to different swipe view?
You can simply break your string comprising of a special character like this :-
String str ="mynameisjhon.yournameisdash.bla";
, here you have a string concatenated with " . " (period character)
to break this string do this :-
StringTokenizer st = new StringTokenizer(str, "."); //break the string whenever "." occurs
String temp =st.nextToken(); // it will have "my name is jhon" break
String temp2 = st.nextToken();// it will have "your name is dash"
String temp3 = st.nextToken();//it will have "bla"
now your string is breaked into parts!
Anything else?
Load the whole string into your ViewAdapter and seperate it via substring
or load the string in your Activity/Fragment seperate it via substring, put the strings in an ArrayList, an initiate your ViewAdapter with the ArrayList as data source
either way use substring
I have db with scheme
1. _id
2. word
And i have ArrayList with for example 5 words (a1, a2, a3, a4, a5)
What is the best way to construct query to get words from DB which don't contain words from ArrayList?
Sowthing like
Select * from MYTABLE where WORD not in "all words from
ArrayList"
Build a string representing the set of words, and use that as an argument to the query.
StringBuilder wordSet = new StringBuilder();
wordSet.append('(');
for( String word : wordsList )
{
if(wordSet.length() > 1)
wordSet.append(',');
wordSet.append(word);
}
wordSet.append(')');
Pseudo Query
Select * from mytable
Use the except operator against a selection containing words in array list
http://en.wikipedia.org/wiki/Set_operations_(SQL)#EXCEPT_operator