delete a row in SQLite with a value of null - android

I am trying to delete all rows in an SQLite Database where the Id = null
Here is my code :-
public void deleteNullSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String sql = String.format("ID=%s", null);
db.delete(TABLE_NAME, sql, null);
}
But it does not delete any vlues can't work out what is wrong ?
I have tried different ways of doing this but when i print the contents of the database the rows are still there

You should use IS NULL in your where clause:
db.delete(TABLE_NAME, "ID IS NULL", null);

Related

delete all rows from sql in android studio

my app should delete a specific row in the sql database by this method
public void delete(int id){
open();
sqLiteDatabase.delete("item","id = "+id,null);
close();
}
and it should also delete all rows if the user want that by this method
public void deleteAll(){
cursor=sqLiteDatabase.rawQuery("select * from item",null);
cursor.moveToFirst();
i=1;
while (!cursor.isAfterLast()) {
sqLiteDatabase.delete("item","id = "+i,null);
i++;
System.out.println(i);
cursor.moveToNext();
}
}
when the user use deleteAll() alone it is work but when he use it after using delete() it delete all rows before the deleted one using delete()
is the problem in deleteAll() method ? and how to fix it?
Your delete() function only deletes rows with the given id. If you want to delete all rows, then just do
sqLiteDatabase.delete("item", null ,null);
There is no reason to write your own loop especially since you never use the Cursor anyway.
Additionally, you should never use string concatenation for the "where" clause in a SQL statement. Instead use "id = ?" and provide a String[] with the values:
db.delete("image","id= ?", new String[] {id});
Here is an example of how to delete a particular column with an id:
SQLiteDatabase db= this.getWritableDatabase();
db.delete("image","id= ?", new String[] {id});
Toast.makeText(context,"Delete successfully",Toast.LENGTH_LONG).show();
Hope this will work for you

Queries in SQLite

I have the following insert statement in my app which work.
Before the insert I want to first check the database if the value name does not exist in the name column.
If it does not exists I want to continue with the insert, else display an error message.
How do I incorporate it into my existing statement below?
public void insert(HashMap<String, String> queryValues){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
Cursor c = database.query("SELECT * FROM user_details where" + "name=?", new String[] {values.put("name") });
if (c.getCount() > 0) {
// don't do it
return;
}
else {
values.put("name", queryValues.get("name"));
values.put("age", queryValues.get("age"));
database.insert("user", null, values);
}
database.close();
}
The correct way to do this is to add a unique constraint on the name field, and then use insertWithOnConflict() with a last argument of CONFLICT_FAIL. That's actually the default behavior. Your insert will fail if it would otherwise cause a constraint violation (insert() will return -1).
If you don't want to do that, there's no magic. Query your DB for a row with the given name field. If you are returned >0 rows, don't perform the insert.
Cursor c = db.query(..., "name=?", new String[] {theName}, ...);
if (c.getCount > 0) {
// don't do it
return;
}

How to get execute query string in sqlite for android?

I am using sqlite
i want to print the query executed in db to insert
here is my code
// for SAving Ocean/Air sales
public int saveOrder(Order odr) throws SQLException {
SQLiteDatabase db = con.getWritableDatabase();
int ordrId = 0;
ContentValues values = new ContentValues();
values.put("cr_usr", odr.getCrUsr());
values.put("cr_ts", odr.getCrTs().toString());
values.put("eat_mst_cust_id", odr.getEatMstCustId());
values.put("ordr_dt", odr.getOrdrDt().toString());
String selectQuery = "SELECT last_insert_rowid()";
try {
// Inserting Row
db.insertOrThrow("eat_ordr", null, values);---getting error here for constraint failed
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
ordrId = cursor.getInt(0);
db.close();
} finally {
db.close();
}
return ordrId;
}
I am not getting any error but row is failed to insert bcz it returns 0 for idvalue
so i want to see executed query how to get that query?
here is my table structure
CREATE TABLE "eat_ordr" ("eat_ordr_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"eat_mst_cust_id" VARCHAR NOT NULL REFERENCES "eat_mst_cust"("eat_mst_cust_id"),
"ordr_no" VARCHAR NOT NULL UNIQUE ,
"ordr_dt" DATETIME NOT NULL ,
"ordr_stat" VARCHAR NOT NULL ,
"last_sync_ts" DATETIME,
"cr_ts" DATETIME DEFAULT CURRENT_TIMESTAMP, "md_ts" DATETIME, "cr_usr" VARCHAR, "md_usr" VARCHAR)
The insertOrThrow documentation says:
Returns
the row ID of the newly inserted row
So this can be done much easier:
ordrId = db.insertOrThrow("eat_ordr", null, values);

Inserting data to SQLite table with constraint failure

Inserting data to SQLite table with constraint failure
I'm trying to insert data into SQLite table on Android. _id is primary key of the table and I am inserting a row using this method:
public void addSomeData(int id, String datetime) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, id);
contentValues.put(KEY_DATETIME, datetime);
mDb.insert(TABLE, null, contentValues);
}
The problem I get is that sometimes primary key constraint is validated and I would like to use something like INSERT IF NOT EXISTS, but preferably something that would work with ContentValues. What are my options? I understand that insertOrThrow() and insertWithOnConflict() methods only return different values, or should I use one of these methods?
Use insertWithOnConflict() with CONFLICT_IGNORE.
Will return ROWID/primary key of new or existing row, -1 on any error.
In my case "constraint failure" happened because of I had some tables which are depended on each other. As for the "insert if not exist", you can query with this id and you check if the cursor's count is bigger than zero. Check the method I'm already using in my app.
public boolean isRowExists(long rowId) {
Cursor cursor = database.query(this.tableName, this.columns, DBSQLiteHelper.COLUMN_ID + " = ? ", new String[] { "" + rowId }, null, null, null);
int numOfRows = cursor.getCount();
cursor.close();
return (numOfRows > 0) ? true : false;
}
to do so you could simply query the db to see if a row with that key exists and insert the new row only if the query returns no data.

check value if exist sqlite error insert

i have a method to insert data and check when code is exists or not
if exist dont create insert and if not exists will create insert
but when i try to running the data cant insert to a database
here is my insert code
public void processAddA(DialogWrapper wrapper)
{
ContentValues values = new ContentValues(2);
values.put(DatabaseHelper.CODE, wrapper.getCode());
values.put(DatabaseHelper.ALAMAT, wrapper.getAlamat());
values.put(DatabaseHelper.BATAS, wrapper.getBatas());
values.put(DatabaseHelper.LAT, wrapper.getLat());
values.put(DatabaseHelper.LON, wrapper.getLon());
values.put(DatabaseHelper.LUAS, wrapper.getLuas());
values.put(DatabaseHelper.TANGGAL_AWAL, wrapper.getTglA());
values.put(DatabaseHelper.TANGGAL_AKHIR, wrapper.getTglB());
values.put(DatabaseHelper.USER_ID, wrapper.getUser());
values.put(DatabaseHelper.SENT, "0");
open();
//check if value exist or not.
Cursor c = database.rawQuery("SELECT * FROM petak_tetap where code='"
+ wrapper.getCode() + "'", null);
if(c == null)
{
//doesn't exists therefore insert record.
database.insert("petak_tetap", DatabaseHelper.ALAMAT,
values);
}
close();
}
how to fix that?
use this condition it will work
if (c!=null && c.getCount()==0)
Well first of all c is never null you should use
if (!c.moveToFirst())
But it is a lot easier if you declare your code column to be UNIQUE and then use insertWithOnConflict with SQLiteDatabase.CONFLICT_IGNORE as the last param.

Categories

Resources