Mino Assad
Mino Assad

Reputation: 37

How to query a SQLite database

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.

Upvotes: 3

Views: 179

Answers (4)

Octaviano Putra
Octaviano Putra

Reputation: 644

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

Upvotes: 1

Varun Kumar
Varun Kumar

Reputation: 1261

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

Upvotes: 0

mubeen
mubeen

Reputation: 839

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);

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

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);

Upvotes: 1

Related Questions