Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 573
Mino Assad Avatar asked Jul 09 '26 13:07

Mino Assad


2 Answers

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);
like image 187
ρяσѕρєя K Avatar answered Jul 13 '26 22:07

ρяσѕρєя K


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);
like image 34
mubeen Avatar answered Jul 13 '26 20:07

mubeen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!