I have a query that joins 2 tables get the required data on my android, what picture here is the user clicks on an item and the item's ID is used to query the right data in the Database, I know I can simply use database.query() but it according to my research it is used for simply database querying only, in my case I should use rawQuery() which provides more power of the database. below is my query which links table 1 to table 2 to get the users name from table one and user last name from table 2 if the foreign key is the same as user key
Assume this is my query:
String sQuery = SELECT table1.ID, table2.userlastname FROM table1, table2 WHERE "+table1.ID = table2.foreign;
If i try to specify the user id like below it gets all data in the database table which means i should replace id with "=?" but how do I do this when I am dealing which such a query, one that uses db.rawQuery() instead of db.query()
`private Object userInfo(int id)
{
String sQuery = SELECT table1.ID, table2.userlastname
FROM table1, table2 WHERE "+table1.ID = id;
}`
Basically you replace the parameter by question marks '?' and pass them through a String array in the order they appear in the query.
String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign;
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);
it did not work until I joined table 2 like:
`String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);`
Related
I am in trouble I have 2 table in sqlite and want both field from them but I did not got any thing. I have tried a lot on stack overflow but no one is work for me..
My query is something like that-
public List<HeadItemGroup> getAllExpense() {
List<HeadItemGroup> expenseList = new ArrayList<HeadItemGroup>();
db = sqlHp.getReadableDatabase();
String selectquery = "SELECT table_expense.item_id AS ID,table_item.item_id AS ID2,* FROM table_expense INNER JOIN table_item ON table_expense.item_id=table_item.item_id";
System.out.println("selectquery value..."+selectquery);
cursor = db.rawQuery(selectquery, null);
while (cursor.moveToNext()) {
HeadItemGroup record = new HeadItemGroup();
record.setExpId(cursor.getInt(cursor.getColumnIndex(EXPENCE_ID)));
record.setItemId(cursor.getInt(cursor.getColumnIndex(ITEM_ID)));
record.setHeadId(cursor.getInt(cursor.getColumnIndex(HEAD_ID)));
record.setDate(cursor.getString(cursor.getColumnIndex(EXPENCE_DATE)));
record.setPrice(cursor.getString(cursor.getColumnIndex(EXPENCE_PRICE)));
record.setLocationLat(cursor.getString(cursor.getColumnIndex(LOCATION_LAT)));
record.setLocationLon(cursor.getString(cursor.getColumnIndex(LOCATION_LON)));
record.setLocationName(cursor.getString(cursor.getColumnIndex(LOCATION_NAME)));
record.setCurrency(cursor.getString(cursor.getColumnIndex(CURRENCY_SYMBOL)));
record.setDescription(cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
record.setItemName(cursor.getString(cursor.getColumnIndex(ITEM_NAME)));
record.setGroupId(cursor.getInt(cursor.getColumnIndex(GROUP_ID)));
expenseList.add(record);
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(EXPENCE_PRICE)));
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(ITEM_NAME)));
System.out.println("total value value**************"+ cursor.getString(cursor.getColumnIndex(GROUP_ID)));
}
return expenseList;
}
And when I am trying with same table for left outer join it's work..
String selectquery="select exp_id as _id, * from table_expense d left outer join table_item u on ( d.item_id=u.item_id)";
But i need all data from both table. Please help me...
what do you think my problem is.
I am querying a sqlite database.
This code doesn't give any result.
String sql = " select _id from MYTABLE where _id = ? ";
Cursor cur = mDb.rawQuery(sql, new String[] {"5653"}) ;
but if I am executing the query without parameters like this:
String sql = " select _id from MYTABLE where _id = 5653 ";
Cursor cur = mDb.rawQuery(sql, null) ;
One row is returned as expected.
Many thanks.
That happens because the values are bound as strings, and that column is (i am guessing) an int. so the where clause will end up being
where _id = "5653"
From rawQuery javadoc for selectionArgs -
You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Try this:
String sql = " select _id from MYTABLE where _id = '5653' ";
I am using INNER JOIN on two tables,table1 and table2, from my SQLite Database.
How do I access the results(columns of both tables) from the cursor? The two tables have 2 columns with same name.
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
You can specify column names instead of using '*'.
String query = SELECT table1.id AS ID,table2.column2 AS c2,...... FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
and then access using column name ID,c2 etc .
while (cursor.moveToNext()) {
String c2 = cursor.getString(cursor.getColumnIndex("c2"));
int id = cursor.getInt(cursor.getColumnIndex("ID"));
..............
.............
}
Editing the broken link : Check rawQuery methid here http://www.vogella.com/tutorials/AndroidSQLite/article.html
and here http://www.codota.com/android/methods/android.database.sqlite.SQLiteDatabase/rawQuery for different examples
You can access the result as you would with any other query.
The only difference is that there is a chance to name conflicts, same column name on both tables. In order to solve those conflict you would need to use the table name as a prefix.
For example
Long id = c.getLong(c.getColumnIndex(tableName1 + "." + idColumnName));
If this approach doesn't work. You should write your query as follows:
String query = SELECT table1.id AS table1_id FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
And another general note, it is better not to use "Select *..." it is preferred to write explicitly which column you would like to select.
Cursor c=databseobject.functionname() //where query is used
if(c.movetofirst()) {
do {
c.getString(columnindex);
} while(c.movetoNext());
}
I have used the following to do an inner join:
public Cursor innerJoin(Long tablebId) {
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
return database.rawQuery(query, null);
}
You can Iterate your cursor as below:
Cursor cursor = innerJoin(tablebId);
String result = "";
int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT);
cursor.moveToFirst();
do{
result = result + cursor.getString(index_CONTENT) + "\n";
}while(cursor.moveToNext());
Hope this works for you
If you know the column name then you can find it like below,
long id = cursor.getLong(cursor.getColumnIndex("_id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
if you just want to see all the columns name of the returned cursor then you can use String[] getColumnNames() method to retrieve all the column names.
Hope this will give you some hint.
I am having a problem in SQLiteDatabase. I want to access the database table created in one Activity from another Activity.However when I use WHERE clause the query is not executing.
I am referring sambleDB from CropInfoListclass.
These are some codes.
String[] item = {getIntent().getExtras().getString("item")};
Cursor c = CropInfoList.sampleDB.rawQuery("SELECT * FROM "+ TableName +" WHERE "+ name +"=?", item);
String Name = c.getString(c.getColumnIndex("name"));
String Type = c.getString(c.getColumnIndex("type"));
I am trying to explore android and I just started using SQLite database. I'm wondering on what is the right syntax for selecting a single row from a table, where the row I want to select is from the value entered from a user using editText. Thanks in advance.
I'm going to disagree with both of the answers above. What if the user enters this query:
Bobby Tables'; drop table yourTable;
See: http://xkcd.com/327/
I believe you should do this instead:
String query = "select * from TABLE_NAME WHERE column_name=?";
String[] selection = new String[1];
selection[0] = users_entered_value;
Cursor c = db.rawQuery(query, selection);
ETA: Actually, the more I think about it, the more I think you're going in the wrong direction. If your app depends on a database query returning exactly one unique match to an arbitrary string entered by the user, it's probably going to be broken a great deal of the time.
What you should probably do is something like this:
String query = "select * from TABLE_NAME WHERE column_name LIKE ?";
String[] selection = new String[1];
selection[0] = "%" + users_entered_value + "%";
Cursor c = db.rawQuery(query, selection);
and then iterate through the results and pick a "best" match according to your own criteria.
Also, you should create the table with case-insensitive matching for the column(s) you're going to be searching.
SQLiteDatabase db;
db.rawQuery("select * from yourTable where your_column_name = 'users_entered_value' limit 1", null);
SQLiteDatabase db;
// make connection to your database ;
Cursor c = null ;
String SQL = "select * from TABLE_NAME where column_name='VALUE'";
c = db.rawQuery(SQL);
c contains your result array of query you fired.
You can retrieve values using loop.