I have a query that pulls everything from a database into a list view.
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_HEIGHT,
KEY_BODY, KEY_HOMEID},null , null, null, null, null,null);
| String Having is the 3rd from
last null.
I want only the records where the field KEY_HOMEID matches a variable called journalId which should be a numeric string.
I would also like to know how to bring the variable into my DatabaseAdapter...
would ((resource) this.getApplication()).getjournalId()) work?? resource is a class that extends application.
Firstly, posting error messages rather than "no dice" would be helpful.
Secondly, please read the documentation for SQLiteDatabase.query(). SQL keywords like "FROM" and "HAVING" shouldn't form part of the method call.
You've already passed the table name as the first parameter to query(), so writing "FROM DATABASE_NAME WHERE ..." is both redundant and will lead to an invalid query being formed.
Thirdly, you can't pass in Java variable names as part of the selection parameter String — you need to have a String like: KEY_HOMEID +"="+ journalId.
Fourthly, it's generally a good idea to use selectionArgs rather than embedding the query parameters into the selection. Especially when you have Strings or parameters coming from user input.
e.g. selection = KEY_HOMEID +"=?" and selectionArgs = new String[] { journalId }
Overall, your method call should look like:
mDb.query(DATABASE_TABLE,
new String[] { KEY_ROWID, KEY_HEIGHT,
KEY_BODY, KEY_HOMEID },
KEY_HOMEID +"=?", new String[] { journalId },
null, null, null);
Use a WHERE clause; HAVING is only used with GROUP BY.
Related
This query keeps returning errors like error near ?.
public Cursor getRow2( String st, String dr) throws SQLException {
String whereClause = "(adate ?) AND (station ?)";
String[] whereArgs = new String[] { dr, st };
String orderBy = "adate";
Cursor mCursor = db.query(DATABASE_TABLE, columns, whereClause, whereArgs,
null, null, orderBy);
String dr is for "data-range".
If the user does specify the two dates, then dr gets a value like BETWEEN 2004-03-01 AND 2004-06-01.
Othewise dr gets NOT NULL so that the query finds ALL dates.
String st is for "gas station".
If the user provides the station name, st gets a string like 'Shell'.
Otherwise st gets NOT NULL so as to find ALL stations.
Thank you very much.
You can use ? to bind only literals, not partial expressions.
(adate ?) AND (station ?) is not a valid expression. Binding the first arg to BETWEEN 2004-03-01 AND 2004-06-01 and the second Shell makes it essentially
(adate 'BETWEEN 2004-03-01 AND 2004-06-01') AND (station 'Shell')
which is syntactically incorrect.
To use bind args with a query like this, make the query like
(adate BETWEEN ? AND ?) AND (station = ?)
binding args as "2004-03-01", "2004-06-01", "Shell".
For the "not specified" cases it's probably best to use different queries altogether.
How can I make query using SQLiteDatabase.query ?
"Select * from table where col1 = something AND col2 IS NOT NULL"
I tried it by putting the col2 with a =? in selection String and NOT NULL in selection argument but it doesn't work.
Please tell me where m going wrong.
selectionArgs is an array of strings, and can be used only for string values.
When you use col2 = ? with the string NOT NULL, you are telling the database to check if the column's value is the eight-character string "NOT NULL".
You must write col2 IS NOT NULL directly into the selection string:
db.query("MyTable", null,
"col1 = ? AND col2 IS NOT NULL",
new String[] { "something" },
null, null, null);
You can use Cursor and rawQuery
Cursor c=db.rawQuery(your_query,null)
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns
A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection
A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs
You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy
A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having
A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy
How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
So you can try like this
String[] args = { "first string", "second#string.com" };
Cursor cursor = db.query("TABLE_NAME", null, "name=? AND email=?", args, null,null,null);
hi i have a poem database and i want to search in the poems this is what my code look like now
public ArrayList searchthequeryforme(String inputText) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_TEXT, KEY_TITLE };
Cursor c = mydatabase.query(true,TABLE_POEM, columns, KEY_TEXT+" like '%"+inputText+"%'", null, null,
null, null, null);
ArrayList<poem> myarray = new ArrayList<poem>();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
poem = new poem(c.getInt(0), c.getString(1), c.getString(2));
myarray.add(poem);
}
return myarray;
}
but in this case if i search for "poem" for example it retrieves the records in which i have "poet" and it comes with a text that actually doesnt have "poem" i want to get the exact records what should my query look like?
That's what the LIKE operator does. To get an exact match, change
KEY_TEXT+" like '%"+inputText+"%'"
to
KEY_TEXT+"='"+inputText+"'";
If you are interested in using framework instead of coding the database access code, then, please look at Active Android (http://www.activeandroid.com/). It has some very nice query access API as you can from examples here: https://github.com/pardom/ActiveAndroid/wiki/Querying-the-database
I'm writing a method to update default settings in a table. The table is very simple: two columns, the first containing labels to indicate the type of setting, the second to store the value of the setting.
At this point in the execution, the table is empty. I'm just setting up the initial value. So, I expect that this cursor will come back empty. But instead, I'm getting an error (shown below). The setting that I am working with is called "lastPlayer" and is supposed to get stored in the "SETTING_COLUMN" in the "SETTINGS_TABLE". Here's the code:
public static void updateSetting(String setting, String newVal) {
String table = "SETTINGS_TABLE";
String[] resultColumn = new String[] {VALUE_COLUMN};
String where = SETTING_COLUMN + "=" + setting;
System.err.println(where);
SQLiteDatabase db = godSimDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(table, resultColumn, where, null, null, null, null);
System.err.println("cursor returned"); //I never see this ouput
\\more
}
sqlite returned: error code = 1, msg = no such column: lastPlayer
Why is it saying that there is no such column lastPlayer? I thought that I was telling the query to look at the column "SETTING_COLUMN" and return the record where that column has a value "lastPlayer". I'm confused. Can somebody straighten me out? I've been looking a this for an hour and I just don't see what I am doing wrong.
Thanks!
You're not properly building/escaping your query. Since the value lastPlayer is not in quotes, your statement is checking for equality of two columns, which is what that error message is saying.
To properly build your query, it's best to not do this manually with String concatenation. Instead, the parameter selectionArgs of SQLiteDatabase.query() is meant to do this.
The parameters in your query should be defined as ? and then filled in based on the selectionArgs. From the docs:
You may include ?s in selection, which will be replaced by the values
from selectionArgs, in order that they appear in the selection. The
values will be bound as Strings.
So, your code would look like this:
String where = SETTING_COLUMN + " = ?";
Cursor cursor = db.query(table, resultColumn, where, new String[] { setting }, null, null, null);
Dear Stack Overflow Community,
I have a question regarding how to incorporate a WHERE clause when querying a sql database in Android. My goal is to return specific records from my database where the date picked by a datepicker matches the date stored.
Here is my code:
private static String datePickerDate = "3/29/2011";
private static String[] FROM = { _ID, NAME, PRICE, DATE, TIME };
private static String ORDER_BY = TIME + " DESC ";
private static String WHERE = DATE + "is like " + datePickerDate;
private Cursor getEvents(){
// Perform a managed Query. The Activity will handle closing
// and re-querying the cursor when needed
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
My questions are thus:
Where does my "WHERE" statement go?
And is my "WHERE" statement correct?
The documentation I found for db.query doesn't specify if a "WHERE" clause can be used, it just specifies that a "HAVING" clause is possible, but I don't quite think that's what I'm wanting.
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
The selection represents your WHERE clause.
From the doc
selection A filter declaring which
rows to return, formatted as an SQL
WHERE clause (excluding the WHERE
itself). Passing null will return all
rows for the given table.
So you can try this (untested):
private static String WHERE = "DATE like ?";
db.query(table, columns, WHERE , new String[] { datePickerDate }, groupBy, having, orderBy)
If you want to use the WHERE clause, I would suggest using the raw query function in the SQLiteDatabase class, shown here.
This way, you can have the raw query typed out (or in segments) as if you were doing it naturally with SQL.
EDIT: On a side note, the "selection" parameter of the query() function corresponds to the WHERE clause, as noted here
About where you're "WHERE" goes - look here
And regarding the second part, I think you miss the qouts before and after the value, it should be .. like '3/29/2011' and not .. is like 3/29/2011