Unable to delete a row in SQLite database in my app - java

I need to delete a specific row from table in my SQLite database.
This table contains paths to files.
And I need to delete paths, which contain specific extensions.
And I have troubles with this.
Nothing is deleted from my database.
For example my table name is ALL_PATHS and column name is PATH_NAME
This is the way I am doing this.
I'll be very glad for any help thanks
private void deletePath(String extension){
Database db = getWritableDatabase();
String query = "DELETE FROM " + ALL_PATHS + " WHERE lower(" + PATH_NAME + ") LIKE '%" + extension + "'";
Cursor cursor = db.rawQuery(query, null);
}

The error is:
Cursor cursor = db.rawQuery(query, null);
While it should be
db.execSQL(query);
Because DELETE is a command, not a query (SELECT)

use Content values
String table = "beaconTable";
String whereClause = "_id" + "=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);

Related

How to check if row exists or not before insertion?

I want to insert records to my sqllite database but before insertion i have to check if the record exists .
I used this code but still say no such column and stopped working although the record exists .
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TEAM + " WHERE "
+ TEAM_TABLE_NAME + " = " + name+";";
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
return true;
}
return false;
This is the recommended way to use rawQuery():
String selectQuery = "SELECT * FROM " + TABLE_TEAM + " WHERE " + TEAM_TABLE_NAME + " = ?";
Cursor c = db.rawQuery(selectQuery, new String[] {name});
so you pass name as a parameter to the query and avoid the risk of sql injection.
In your code you only check if the Cursor object is null and not if it contains any rows which is the right thing to do.
So return the result of getCount() > 0 like this:
return c.getCount() > 0;
This will return true if the name already exists in the table.
As for the no such column error, this is something different.
First make sure that TEAM_TABLE_NAME is the correct name of the column and if it is then maybe you made changes to the names of the columns tha are not reflected to the database.
So uninstall the app from the device so the database is deleted and then rerun to recreate the database with the new names of the columns.

error occur when try to SELECT in sqlite android

so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM

Android / Java: How to get last row value in sqlite?

Hello I am using a sqlite database in my android application, and I have question:
I am trying to get the last value text(thats the collumn) from the last row from the table TABLE_XYZ... but it does not work.. i am using the following code...what am I doing wrong?
another question is, how can I return two values instead of only one, when I want to get several values from the last row like column text and message?
private static final String KEY_MESSAGE = "message";
private static final String KEY_TEXT = "text";
...
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.close();
return cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
EDIT:
i hade some errors in my Query,, i fixed it, but still have errors:
String selectQuery= "SELECT * FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = cursor.getString( cursor.getColumnIndex(KEY_TEXT );
cursor.close();
return str;
while debugging I can see that cursor does have the right values inside... but when i try to get the column value with this command "cursor.getString( cursor.getColumnIndex(KEY_TEXT );"... it does not work...
you are closing cursor before getting it's value
try this :
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = "";
if(cursor.moveToFirst())
str = cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
cursor.close();
return str;
From the android documentation: http://developer.android.com/reference/android/database/Cursor.html
abstract void close()
Closes the Cursor, releasing all of its resources and making it completely invalid.
You are closing the cursor before returningthe string.
Like #whatever5599451 said you should not close the cursor before you get value. Also try a query like this:
String selectQuery = "SELECT column FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
You can specify the columns also specify to return only 1 row.
This will bring back only the column you are ordering by you can also specify more columns example:
String selectQuery = "SELECT column, column2, column3 FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
* means select all columns
to get the last column, use the name of the column instead of " * " (* means all, all the fields)
#Steve: do this:
String selectQuery= "SELECT " + KEY_TEXT + " FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
then you get just one String with the last record containing just the right column

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();
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();
Is the id column title actually "ID"? Or is that a variable that is set to "_id" (the usual column name for the primary key in an Android database)?
If the latter, your query is not right, because you are using "ID" as the literal column name. Try changing it to this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE " + ID + " = " + id, null);
or even this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE _id = " + id, null);
try using
Cursor cursorc = db.rawQuery("select * from list where ID = ?", new String[] {id+""});
try with this way
Suppose long id=5;
String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_ADDRESS}; // your column which data u want to retrive if id is same
Cursor c=db.query(DATABASE_TABLE, col, KEY_ROWID+"="+id,null, null, null, null);
if(c!=null){
c.moveToFirst();
// get data here which u want accroding to ur requirement
}
try this
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID='"+id+"'", null);

Android sqlite helper error while getting data back

Hi all im using a sqlite helper class, but i have a little problem using a select statement.
I want to get the id of a datebase item by its name.
I use this select method:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, "name=" + name, null, null, null, null);
c.moveToFirst();
db.close();
return c;
}
And when i call this i use this:
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
id = c.getInt(c.getColumnIndex("_id"));
c.close();
}
And then is get this error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
As if its not exists, but i checked the name string is correct, and when i display the names in a listview i see that name, so it exists.
Can someone help me how to fix this?
1 - there shoudld be check is there any data in cursor or not......c.getCount>0 or c.moveToFirst() or c.isAfterLast().......
if(handler.selectShift(name)!=null){
Cursor c = handler.selectShift(name);
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();
}
2- not sure but looks in select query as '<variable>' are not there in where clause with variable
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
The issue appears to be here
"name=" <-It should be "name = "+name
Following should work
Cursor cursor= db.query(TABLE_IMAGES,null, "name" +" = ?", new String[]{name}, null, null, null);
Unless your name variable is already formatted (or not a TEXT) for sql I am guessing you need a little quotation. Maybe something like this
Cursor c = db.query(TABLE_NAME, null, "name= \'" + name + "\'", null, null, null, null);
Thanks for your help, i found the problem. It was in the cursor method, the solution is:
public Cursor selectShift (String name){
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {"_id"}, "name LIKE '"+name+"%'", null, null, null, null);
c.moveToFirst();
db.close();
return c;
}

Categories