How can i write join query in android sqlite? - android

Hi, I am new to android. I want to write query for join in sqlite. My code is -
public Cursor SearchCategory(SQLiteDatabase db){
//return db.query("category_master", null, "status = 'Active'", null, null, null, null);
String Category_Sql = " select category_master.*,count(*) as cnt from product_master " +
" left join category_master on product_master.category_id = category_master.category_id " +
" where category_master.status = 'Active' group by category_master.category_id having cnt > 0 ";
return db.query(Category_Sql);
}
but it generate error. Where am I wrong?

It would have helped more if you could cite the error description.
Try running the query first in Portable SQLite explorer

you can use rawQuery
db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null);
it should work

Related

SQLITE: Count column values

I have some code like this:
public void gameOverCheck() {
SQLiteDatabase database = this.getWritableDatabase();
database.execSQL("SELECT " + COL_ROLE + " COUNT");
database.close();
}
in android. And would like to count the values of COL_ROLE (which has one of two possible values (mafia, civilian)). So if the number of Mafia >= Civilian game = mafias win. If Mafias = 0, game = civilian won. I am struggling with the SQL command to do the first part, am I supposed to group the values?
Try this:
Cursor mCount= db.rawQuery("select count(*) from your_table where " + COL_ROLE + " = 'mafia'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();`

How to merge two cursor in resultant cursor?

I am working with sqlite where i have fired a query with "IN" operator but its taking to much time to display data. My query is following :
String Sql_query = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST where PARTY_KEY in( Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Now to reducing time to get data i have made two cursors like below :
String Sql = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST";
String Sql2 = "Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Cursor c1 = dbhelper.showdata(this,Sql);
Cursor c2 = dbhelper.showdata(this,Sql2);
Now i want to merge this two cursors c1 and c1 in one cursor like c1 + c2 = main_cursor
I have merged both cursor like following code :
MergeCursor merge_cursor = new MergeCursor(new Cursor[] {
c1, c2});
But it not worked in merge_cursor i getting only data of first cursor (c1).
Is it possible ? Please guide if anybody face this type of proble
Any other way to write this query ?
Thank you in advance.
You can use Join or Union for it.
Like for an example :-
sql = sql1;
sql += " UNION "
sql += sql2;

Issue with my sqlite query in Android application

I've got a problem with my Android application. I'm trying to query database with multiple tables and display the result in the application. It's a dictionary. The problem is my query doesn't work. I have no clue what I'm doing wrong.
Here is a sample of my code that I use for it. If you need any more information, just let me know.
Thank You.
try {
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT index_nom_adresse" + word[0].toLowerCase().trim() + " FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ", null);
//Cursor cursor = dictionary.getDictionaryDatabase().query("adresse_definition", null, "index_nom_adresse= '" + word[0].toLowerCase().trim() + "' or definition= '" + word[0].toUpperCase().trim() + "' ", null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
if (word[1] == null || word[1].equals("English")) {
translatedWord = cursor.getString(2);
} else {
translatedWord = cursor.getString(1);
}
} else {
translatedWord = "The word is not in database";
}
cursor.close();
} catch (SQLiteException sqle) {
translatedWord = "The word is not in database";
}
here is a logCat i get when trying to search for word
03-20 14:34:17.341: I/SqliteDatabaseCpp(516): sqlite returned: error code = 1, msg = no such column: index_nom_adressebonbon, db=/data/data/com.example.application/databases/dict.db
The query should be:
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT index_nom_adresse" + word[0].toLowerCase().trim() + " FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ", null);
otherwise the coulmn is not defined correctly.
First of all, your hiding the real error by catching the Exception and then say "the word is not in the database'.
The problem your likely to have, which is just a guess because of the limited amount of information you are giving, is passing the word in the SELECT, instead of in the WHERE clause.
Likely your SQL query needs to be something like this:
SELECT index_nom_adresse
FROM adresse_definition
JOIN definition ON adresse_definition.definition = definition.data_id
WHERE index_nom_adresse = word[0].toLowerCase().trim() OR definition = word[0].toUpperCase().trim()
This translates to:
String sql = "SELECT index_nom_adresse ";
sql += "FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ";
sql += "WHERE index_nom_adresse = " + word[0].toLowerCase().trim() " OR definition=" + word[0].toUpperCase().trim();
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery(sql, null);
or (a better solution) (No clue how you would do the join, is the JOIN needed?)
Cursor cursor = dictionary.getDictionaryDatabase().query(
"adresse_definition",
new String[] {"index_nom_adresse"},
"index_nom_adresse= ? OR definition=?'",
new String[] {word[0].toLowerCase().trim(), word[0].toUpperCase().trim()},
null,
null,
null);
Please read up on Android and SQL: http://www.vogella.com/articles/AndroidSQLite/article.html
I have no tools here to validate the code, please comment or edit if there are errors.

SQLite Query in Android to count rows

I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

How do I join two SQLite tables in my Android application?

Background
I have an Android project that has a database with two tables: tbl_question and tbl_alternative.
To populate the views with questions and alternatives I am using cursors. There are no problems in getting the data I need until I try to join the two tables.
Tbl_question
-------------
_id
question
categoryid
Tbl_alternative
---------------
_id
questionid
categoryid
alternative
I want something like the following:
SELECT tbl_question.question, tbl_alternative.alternative where
categoryid=tbl_alternative.categoryid AND tbl_question._id =
tbl_alternative.questionid.`
This is my attempt:
public Cursor getAlternative(long categoryid) {
String[] columns = new String[] { KEY_Q_ID, KEY_IMAGE, KEY_QUESTION, KEY_ALT, KEY_QID};
String whereClause = KEY_CATEGORYID + "=" + categoryid +" AND "+ KEY_Q_ID +"="+ KEY_QID;
Cursor cursor = mDb.query(true, DBTABLE_QUESTION + " INNER JOIN "+ DBTABLE_ALTERNATIVE, columns, whereClause, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
I find this way to form queries harder than regular SQL, but have gotten the advice to use this way since it is less error prone.
Question
How do I join two SQLite tables in my application?
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
An alternate way is to construct a view which is then queried just like a table.
In many database managers using a view can result in better performance.
CREATE VIEW xyz SELECT q.question, a.alternative
FROM tbl_question AS q, tbl_alternative AS a
WHERE q.categoryid = a.categoryid
AND q._id = a.questionid;
This is from memory so there may be some syntactic issues.
http://www.sqlite.org/lang_createview.html
I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.
In addition to #pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this
SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1
via raw query like this -
String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
+ " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
+ " WHERE " + RefuelTable.ID + " = " + id;
Cursor c = db.rawQuery(
rawQuery,
null
);
because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -
SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1
and hence be able to take advanatage of the SQLiteDatabase.query() helper method
Cursor c = db.query(
RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
null,
null,
null,
null
);
For a detailed blog post check this
http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery
"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.
Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.
select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)

Categories

Resources