SQLIte Query, select everything that equals - Android - android

// get friends
public Cursor getFriends(){
Cursor c = dataBase.query(SqConstants.FRIENDS_TABLE_LOCAL, null, null, null, null, null, null);
return c;
}
I have multiple tables in a SQLite database in my application for android.
I want to select everything from a column in a Friends Table (which holds integers) and select everything that equals that integer from a User Table (in the primary column which also is integer) and the get all the users which equals the numbers stored in the friends column.
It was some while I managed SQL databases but I think the query for a MySQL database would be something like:
SELECT * UsersID FROM TABLE Users EQUALS LOCAL_FRIENDS_ID FROM TABLE Friends
I might be wrong that it would look like this, but something like it.
What I want is to do this in android code, from a cursor get all the Users from the Users table which ID is equal to the FriendsID.
How do I change the above method to make it so?

You could just use the rawQuery
Cursor c = dataBase.rawQuery(SELECT * UsersID FROM TABLE Users EQUALS LOCAL_FRIENDS_ID FROM TABLE Friends, null)
If you need to use a actual parameter for the LOCAL_FRIENDS_ID
string[1] args = new String[LOCAL_FRIENDS_ID.ToString()];
Cursor c = dataBase.rawQuery(SELECT * UsersID FROM TABLE Users EQUALS ? FROM TABLE Friends, args)

Related

Sqlite select email column from content provider

I'm trying to select some data from sqlite, where the column represents an email address.
My query is like this:
Cursor countCursor = mContentResolver.query(
SubscribeContract.SubscribeEntry.CONTENT_URI,
new String[]{"count(*) AS count"},
"user = ? ",
new String[]{ userChatID },
null);
But it's returning nothing.
Querys on sqlite3 terminal is returning ok.
sqlite> select count(*) as count from subscribe where user = 'brunox17_7a84e0c5e635fb571b32f5be9d55dd0b734c2f57#boo-app.com';
count
21
I think the problem is because the column type is text, and I cant put quotes surrounding the selection arguments.
What API version are you testing on? The parametrized queries are supported from API11.
You can try the getCount() method on the Cursor object without specifying any where clause.

SELECT entry in SQLite, without a WHERE condition?

I followed advice in this question, but for my purposes I don't want a WHERE.
I don't know the value, so I cannot say rawQuery("... WHERE x = ?", y), I don't care what y is, it's just a cell I want, and it is known that there is a single row.
If it is not possible to lose the condition (perhaps because of causing an indeterminate number of results?) - then how can I say "from column z and row 0"?
I'm lacking either terminology, or outright understanding, because my searches are turning up nothing.
Edit: Eclipse doesn't complain at:
result = db.rawQuery("SELECT col FROM tbl", my_unused_string_array);
I'm not at a testing stage yet, and I can't enter this into the SQL db reader I was using to test SELECT col FROM tbl and ~ with WHERE.. will it work?
As per your edit, you don't need to specify WHERE clause, if you want to get all the records from a table:
result = db.rawQuery("SELECT col FROM tbl", new String[0]);
The SQL query "SELECT * FROM table" will return the entire table. "SELECT colX, colY FROM table" will return columns colX and colY for all the rows in the table. If your table contains just one row, "SELECT col FROM table" will return the value of col for that one row.
To use the SQLiteDatabase API to make that query, you would say:
result = db.rawQuery("SELECT col FROM tbl", null);
... because you are not supplying any query parameters.
Assuming that there is just one row seems dangerous to me. I would not use the "LIMIT" clause, because, while that will always get one row, it will hide the fact that there is more than one row, if that happens. Instead, I suggest that you assert that the cursor contains one row, like this:
if (1 != result.getCount()) {
throw Exception("something's busted");
}
Instead of Raw query use
Cursor cur = db.query(Table_name, null, null, null, null,
null, null);
and get the desired attributes from cursor.
where the query method has parameters in following manner:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
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.
Returns
A Cursor object, which is positioned before the first entry.

Selecting int values using a cursor query

I am new to Android, and having some basic problems. One of them is the use of queries.
I store a boolean value as either 1 or 0 in the table (INTEGER field). However, when I select either on 1 or 0 using the query below I get no results. What am I doing wrong?
Cursor cursor = _db.query(_objectName, _fields.keySet().toArray(new String[0]), "parentId=? AND published=?", new String[] {String.valueOf(menuItem), String.valueOf(1)}, null, null, "level");
There is nothing wrong with your query. The problem must be elsewhere. Check your code and table structure. Maybe you are not sending the right values for parentId and published columns or the data in the table is not in the format you expected.
Use raw query
"Select * from "+TABLE_NAME+" where published = '"+String.valueOf(1)+"'";
You can put your integer value insted of 1

How to get 5 last record in the sqlite db in android?

Since the db does not have create date and some ordering field (but in my observation the last row is the latest record),
so how can i get the five last record in some condition e.g.
five record that their schoolid == 1?
Thanks
public Cursor select()
{
String orderBy = FIELD_pubKey+" DESC";
Cursor cursor = iReadDatabase.query(TABLE_NAME, null, null, null, null, null, orderBy);
cursor.moveToFirst();
return cursor;
}
There's no such thing as a last record or a first or a 42nd.
Which records appears last in the result of a query is dependent on the query plan, or an Explicit order by if you add one.
Select * From Table Where ...
The rows will be returned in whatever order the engine considers suitable at the time.
If you need them in specific order, then add an order by clause to the query, anything else is asking for it.
Something like
Select * From Table Order by SomeColumn desc limit 5
will do what you require.
Now what column you need to order by I've no idea, but you need one that will do the job, assuming automatic primary key, but note it is possible to mess with that.

how to get a row ID from a Cursor

How do I get the row ID from a Cursor?
I don't think the Cursor exposes this directly.
SQLiteDatabase.insert() returns the row id of the newly inserted row. Or in Android the convention is that there is a column named "_id" that contains the primary autoincrement key of the table. So cursor.getLong(cursor.getColumnIndex("_id")) would retrieve this.
I had this same problem where the column index for the primary key was reported as -1 (meaning it isn't there). The problem was that I forgot to include the _ID column in the initial SELECT clause that created the cursor. Once I made sure it was included, the column was accessible just like any of the others.
Concerning the last sentence of Nic Strong's answer,following command didn't work for me. cursor.getColumnIndex("_id") was still -1
cursor.getLong(cursor.getColumnIndex("_id"))
Maybe there's some other issue in my configuration that's causing the problem?
Personally I've taken to maintaining my own custom unique id column in each table I create; A pain, but it gets around this issue.
return sqlite_db.query(table, new String[] { "rowid", "*" }, where, args, null, null, null);
In my case I have "rowid" in DataManager.FIELD_ID and this is SQLite identity column (each table in sqlite has this special kind of column), so I don't need any of my own custom unique id column in tables.
Cursor cursor = mySQLiteHelper.getReadableDatabase().query(TABLE_NAME, new String[] { "ROWID", "*" }, where, null, null, null, null);
then
long rowId = cursor.getLong(0);
As long as the TABLE is not defined using WITHOUT ROWID you can get the ROWID (or should that be rowid see below for case) if you specify it as a column to be retrieved.
For example for a table with 3 defined columns (Names, Colour and Age) with no conventional _id column. The following rawQuery works and returns the ROWID :-
Cursor csr = db.rawQuery("SELECT Names, Colour, Age, ROWID FROM " + TABLE_NAME,null);
Note! that the column name in the cursor is lowercase as per :-
Note! ROWID in the SELECT SQL is case independent (e.g. RoWiD works).
Using
Cursor csr = db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
WILL NOT return the ROWID (likewise for null for the columns when using the query method).
Using query (as opposed to rawQuery) works in the same way, that is you need to specifiy ROWID (note alternatives to ROWID below) as a column to be retrieved e.g. :-
Cursor csr = db.query(TABLE_NAME,new String[]{
"OiD",
"Names",
"Colour",
"Age"
},null,null,null,null,null);
Alternatives to ROWID
Instead of ROWID, you can also use _ROWID_ or OID (case independent) as the column name in the query noting that the column name in the resultant cursor is rowid i.e. it is lowercase.

Categories

Resources