Reputation: 101
I have a problem with Android sqlite and cursor, I want to verify that the value entered in a text box is not in my database.
ContenuBDD contenuBdd = new ContenuBDD(MainActivity.this);
contenuBdd.open();
if(contenuBdd.recherche(text.getText().toString())== true)
{
System.out.println("ok");
}
else
{
System.out.println("not ok");
}
contenuBdd.close();
code of search method :
public boolean recherche(String titre){
Cursor c = bdd.query(TABLE_CONTENU, new String[] {COL_ID, COL_VALEUR}, COL_VALEUR + " LIKE \"" + titre +"\"", null, null, null, null);
if(c == null)
{
return true;
}
else
{
return false;
}
}
For now, even if I enter a value that is not in the database, "not ok" is displayed
my request :
String query = new String( "select valeur from table_contenu where valeur = "+titre);
my logcat :
02-12 10:51:02.338: E/AndroidRuntime(11642): android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: select valeur from table_contenu where valeur =
Upvotes: 0
Views: 130
Reputation: 81539
As I mentioned in my answer at https://stackoverflow.com/a/24144236/2413303
The way you're supposed to do a query is the following:
private String[] allColumns = { Table1.COLUMN_ID, Table1.COLUMN_NAME,
Table1.COLUMN_OTHERCOLUMN };
public ItemDB findEmployeeById(long id)
{
ItemDB employee = null;
Cursor cursor = database.query(ItemTable.TABLE_NAME, allColumns, ItemTable.COLUMN_ID + " = ?", new String[] {""+id}, null, null, null);
if(cursor.moveToFirst())
{
employee = createItemFromCursor(cursor);
}
return employee;
}
Another possible way is using rawQuery
if you need to specifically rename a column (for example, the id
to _id
because the adapters demand it):
public Cursor getRawQueryCursor()
{
return database
.rawQuery(
"SELECT id as _id, name, dateFrom || ' - ' || dateTo as date FROM " + ItemTable.TABLE_NAME + " WHERE lower(name) = ?",
new String[] { inputName });
}
Upvotes: 1
Reputation: 34360
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue)
{
db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + "="
+ fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <=0)
{
return false;
}
return true;
}
Upvotes: -1
Reputation: 519
You should prefer to test :
if(c.getCount() == 0)
instead of
if(c == null)
And maybe your could manage it with a raw query like :
String q = "SELECT * FROM your_table WHERE titre = titre";
Cursor c= mDb.rawQuery(q, null);
Upvotes: 1
Reputation: 18123
I assume, SQLite always returns a Cursor
, but in case of nothing found, Cursor#getCount()
will result in 0
, as displayed in the API.
Upvotes: 0