Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of IN keyword in android sqlite

Tags:

android

sqlite

I have two tables:

1) Employee -- _id, employee_name.
2) Salary -- _id, amount, emp_id.

Sample data:

Employee:
1 John
2 Rocky
3 Marry

Salary:

1 500 1 //salary for John
2 400 1 //salary for John
3 600 2 //salary for Rocky
4 700 2 //salary for Rocky
5 350 3 //salary for Marry

Now, i want to search in salary table to view the whom i have paid the salary. let say if i search for 'John' in salary table, it should return the row 1 and 2 which are for John.

Here is what i am trying:

String where = " emp_id in (select _id from Employee where employee_name like ? )";

String[] whereArgs = new String[] {"'%" + mFilter + "%'" };

Cursor c = getDB(mContext).query("Salary", null, where, whereArgs,
                null, null, null);

But it is always returning no results. Please help.

Update

I debugged the code, and found following query is executing in cursor:

SELECT * FROM Salary WHERE emp_id in (select _id from Employee where employee_name like ? );
like image 580
mudit Avatar asked Aug 01 '13 03:08

mudit


People also ask

What is as in SQLite?

Most programmers will specify the AS keyword when aliasing a column name, but not when aliasing a table name. Whether you specify the AS keyword or not has no impact on the alias in SQLite. It is a personal choice in SQLite, unlike other databases.

What is RawQuery in Android SQLite?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.

Can SQLite be used in Android?

SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app.

What is primary key in SQLite?

In SQLite, a primary key is a single field or combination of fields that uniquely defines a record. A table can have only one primary key. TIP: While the SQL-89 and SQL-92 standards do not allow a NULL value in a primary key, SQLite does allow a NULL under certain circumstances.


1 Answers

Selection args are automatically used as strings. Change this:

String[] whereArgs = new String[] {"'%" + mFilter + "%'" };

To This:

String[] whereArgs = new String[] {"%" + mFilter + "%" }; (removed ' from your strings)

With extra ' in there it cancels out the text and becomes ''%John%'' The builder automatically handles ' for the selection args.

EDIT
Change your query also to this:

String sql = "SELECT * FROM Salary WHERE emp_id in (select _id from Employee where employee_name like ?)";
Cursor c = getDB(mContext).rawQuery(sql, whereArgs);

EDIT 2

I recreated your setup with the class below and all my code ran just fine. I pulled from user John and got both results. I believe that the problem is within your database creation or you just do not have data within your database. Use DDMS to pull the database and open it with SQLite Browser. Check to see if your database has any data within it. If it does then your table creation types do not match the select statement. When I call GetMyValues() I get 2 records returned from the cursor.

public class DataBaseHandler extends SQLiteOpenHelper {

    private static final String TAG = "DBHandler";

    //Database VERSION
    private static final int DATABASE_VERSION = 2;

    //DATABASE NAME
    private static final String DATABASE_NAME = "test";

    //DATABASE TABLES
    private static final String TABLE_SALARY = "Salary";
    private static final String TABLE_EMP = "Employee";

    //DATABASE FIELDS
    private static final String SalaryID= "_id";
    private static final String SalaryEmpName = "employee_name";
    private static final String EmpID= "_id";
    private static final String EmpAmt = "amount";
    private static final String EmpSalID = "emp_id";

    //DATABASE TYPES
    private static final String INTPK = "INTEGER PRIMARY KEY";
    private static final String INT = "INTEGER";
    private static final String TEXT = "TEXT";

    //CREATE TABLES
    private static final String CREATE_SALARY_TABLE = "CREATE TABLE " + TABLE_SALARY + "("
                + EmpID + " " + INTPK + "," +  EmpAmt + " " + INT + ","
                + EmpSalID + " " + INT + ")";

      //CREATE TABLE Salary(_id INTEGER PRIMARY KEY,amount INTEGER,emp_id INTEGER)

    private static final String CREATE_EMPLOYEE_TABLE = "CREATE TABLE " + TABLE_EMP + "("
                + SalaryID + " " + INTPK + "," + SalaryEmpName + " " + TEXT + ")";

      //CREATE TABLE Employee(_id INTEGER PRIMARY KEY, employee_name TEXT)

    public DataBaseHandler(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_EMPLOYEE_TABLE);
        db.execSQL(CREATE_SALARY_TABLE);

        insertEmployeeValues(db);
        insertSalaryValues(db);     
    }

    private void insertEmployeeValues(SQLiteDatabase db){
        ContentValues values = new ContentValues();
        values.put(SalaryEmpName, "John");
        db.insert(TABLE_EMP, null, values);
        values.clear();
        values.put(SalaryEmpName, "Rocky");
        db.insert(TABLE_EMP, null, values);
        values.clear();
        values.put(SalaryEmpName, "Marry");
        db.insert(TABLE_EMP, null, values);
        values.clear();
    }

    private void insertSalaryValues(SQLiteDatabase db){
        ContentValues values = new ContentValues();
        values.put(EmpAmt, 500);
        values.put(EmpSalID, 1);
        db.insert(TABLE_SALARY, null, values);
        values.clear();
        values.put(EmpAmt, 400);
        values.put(EmpSalID, 1);
        db.insert(TABLE_SALARY, null, values);
        values.clear();
        values.put(EmpAmt, 600);
        values.put(EmpSalID, 2);
        db.insert(TABLE_SALARY, null, values);
        values.clear();
        values.put(EmpAmt, 700);
        values.put(EmpSalID, 2);
        db.insert(TABLE_SALARY, null, values);
        values.clear();
        values.put(EmpAmt, 350);
        values.put(EmpSalID, 3);
        db.insert(TABLE_SALARY, null, values);
        values.clear();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EMP);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SALARY);
        onCreate(db);
    }

    public int GetMyValues(){
        String mFilter = "John"; 
        String[] whereArgs = new String[]{"%" + mFilter + "%"};
        int count = 0;
        SQLiteDatabase db = this.getWritableDatabase();
        String where = " emp_id in (select _id from Employee where employee_name like ? )";
        Cursor c = db.query("Salary",null, where, whereArgs,null,null,null);
        count = c.getCount();
        c.close();
        return count;
    }
}

Dev Reference:

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

like image 197
ObieMD5 Avatar answered Jan 03 '23 16:01

ObieMD5