SQLite query give different result from mysql - android

I have two table in my sqlite db here is the first table named supplier and here is the second table named product
what I want to do is I want to get the supplier_name in table product by selecting id_supplier in table_product. Here is my query SELECT table_supplier.id_supplier, table_supplier.supplier_name from table_invoice_in, table_supplier where table_invoice_in.id_product = '4' and table_supplier.id_supplier = table_invoice_in.id_supplier
and what I got from that query is I can get the id_supplier but supplier_name gives me 0 value, but when I try the query in mysql, I got the correct result. My question is :
Is this a limitation of sqlite or there are something wrong with my query?
Thank you in advance.

Try using a JOIN:
SELECT table_supplier.id_supplier, table_supplier.supplier_name FROM table_supplier JOIN table_invoice_in ON table_supplier.id_supplier = table_invoice_in.id_supplier WHERE table_invoice_in.id_product = '4'

The problem solved! When we try to query some column(s) from multiple table, make sure that we get the desired result by pointing directly to the column name. Here is my correct code
public Cursor SelectInvoiceInById(String id){
String query = "SELECT product_name from table_product, table_invoice_in where table_invoice_in.id_invoice_in = '"+ id + "' and table_product.id_product = table_invoice_in.id_product";
ReadDB();
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Log.d("RESULT", String.valueOf(cursor.getString(cursor.getColumnIndex(SQLiteHelper.PRODUCT_NAME))));
cursor.moveToNext();
}
}
CloseDB();
return cursor;
}

Related

Issue in Inner Join Query in Android | Trouble in Sqlite query

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...

Fetching last row from sqlite database

I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable.
Any help is appreciated as I am new to SQLite and Android.
Thanks..
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
limit 1 is in your case because you want only last record only

Android Sqlite no result

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' ";

Android: How to access results from Cursor when INNER JOIN is performed?

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.

Before inserting a record in the database to validate that there is

Before inserting a record in the database to validate that there is, for example I have a table that has two fields, table fields VA with Customer, First, I want to validate the field if there is no customer registration and if there insert
That i want to do in android using Sqlite
String sql = "SELECT * FROM TABLE WHERE id = '" + id + "'";
Cursor data = database.rawQuery(sql, null);
After this check by following code
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
Look at SQLite constraints. This really isn't Android-specific; it's a feature of SQLite.
Try this, it works for me.
String[] args = { myDataToCheck };
c = ourDatabase.query(DATABASE_TABLE, columns,
myColumnToCheck + "=?", args, null, null, null);
if (c.getCount() == 0) {
// doesn't exists
}else{
//exists
}
You have 2 possibilities :
1)make a select to check if there is the same key in database, then insert or update.
2)make directly an update. update will return the number of row updated, if the number is 0, so you can do an insert.

Categories

Resources