Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch a row using id sqlite?

This is a simple one! yet, I am missing something. Please help me out. Here, I am trying to fetch values by id, but not able to do so. It is returning same values even after changing id's value.

    db = openOrCreateDatabase("DBSOURCE", 0, null);
    Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID="+id+"", null);
    cursorc.moveToFirst();

    int NameID = cursorc.getColumnIndex("Name");
    int mobilenumberID = cursorc.getColumnIndex("MoblieNumber");

    edName.setText(cursorc.getString(NameID));
    edMobNum.setText(cursorc.getString(mobilenumberID));

    cursorc.close();

    db.close();
like image 550
Adarsh H S Avatar asked Jun 26 '12 11:06

Adarsh H S


People also ask

How do I find the last row ID in SQLite?

SQLite has a special SQL function – last_insert_rowid() – that returns the ID of the last row inserted into the database so getting the ID of a new row after performing a SQL insert just involves executing the last_insert_rowid() command.

Does Rowid change in SQLite?

From the official documentation: “Rowids can change at any time and without notice. If you need to depend on your rowid, make it an INTEGER PRIMARY KEY, then it is guaranteed not to change”. And I add also AUTOINCREMENT so you are sure that the same rowid(s) are not reused when rows are deleted.


1 Answers

1- or better to use parametrized statement

String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new String[] {comment});

2 - use if with conditon c.moveToFirst() or c.getCount() >0 or (!c.isAfterLast())

if (c.moveToFirst()){ 
    do{ 
       //if you not need the loop you can remove that
       id = c.getInt(c.getColumnIndex("_id"));
   }
 while(cursor.moveToNext());
}c.close(); 
like image 115
Dheeresh Singh Avatar answered Oct 31 '22 17:10

Dheeresh Singh