3

This is my table:

private static final String CREATE_TABLE_EMPLOYEES = "CREATE TABLE "+ TABLENAME + "(" +
            COLUMNS[0] + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , " +
            COLUMNS[1] + " TEXT NOT NULL , " +
            COLUMNS[2] + " TEXT NOT NULL , " +
            COLUMNS[3] + " TEXT NOT NULL , " +
            COLUMNS[4] + " TEXT NOT NULL , " +
            COLUMNS[5] + " TEXT NOT NULL  " +
            ");";

And query all data from database:

public List<Employee> getEmployees() {
        List<Employee> employees = new ArrayList<Employee>();
        Cursor cur = db.query(dbHelper.TABLENAME, columns, null, null, null, null, null);
        cur.moveToFirst(); // need to start the cursor first...!
        while(!cur.isAfterLast()) { // while not end of data stored in table...
            Employee emp = new Employee();
            emp.setId(cur.getInt(0));
            emp.setName(cur.getString(1));
            emp.setCharge(cur.getString(2));
            emp.setDepartament(cur.getString(3));
            emp.setPhone(cur.getString(4));
            emp.setEmail(cur.getString(5));
            employees.add(emp);
            cur.moveToNext(); // next loop
        }
        cur.close(); // !important
        return employees;
    }

I want to query all data if employee name =="ali"

Please help me.

4 Answers 4

1

I want to query all data if employee name =="ali".

3rd and 4th parameter is available in query method for adding WHERE clause in query.

Do it as:

Cursor cur = db.query(dbHelper.TABLENAME, columns, 
                      "name=?", 
                      new String[] { "ali" }, 
                      null, null, null);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this, this will also help you prevent from sql injection

   Cursor cur = db.query(dbHelper.TABLENAME, columns, columns[1]+" = ?", new String[]{"ali"}, null, null, null);

Comments

1

Replace

Cursor cur = db.query(dbHelper.TABLENAME, columns, null, null, null, null, null);

with

 Cursor cur = db.query(dbHelper.TABLENAME, columns, columns[1]+" = ?", new String[]{"ali"}, null, null, null);

The 3rd parameter in db.query() method is "selection statement" and the 4th parameter is "selection arguments".

Comments

0

Use this cursor to query all data if employee name =="ali":-

String selection = COLUMNS[x] + " = " + "'" + ali + "'";
Cursor cur = db.query(dbHelper.TABLENAME, columns, selection, null, null, null, null);

Here COLUMNS[x] should be the column containing the employee names and "x" be the respective column number.

This cursor will fetch you only the records/tuples for the employee named "ali".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.