SQLite delete query isn't working. Can anyone tell me how to use db.delete(table, whereClause, whereArgs) method in limit query?!
String query = "DELETE From gpsinfo LIMIT 100 ";
Cursor cursor = db.rawQuery(query, null);
Try this...
Delete from table_name where ID IN (Select ID from table_name limit 100 );
Use execSQL() for SQL like this.
rawQuery() doesn't run the SQL until you move the returned cursor.
Also, you cannot use LIMIT like this.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUMN_NAME+ " = " + "'"+text+"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
Related
As my title question, I want to delete some rows of table on SQLite where contains specific string.
Here are my methods I tried but there are no any row is deleted. I checked table of SQLite database by get it out and put in to DB Browser for SQLite which is downloaded from https://sqlitebrowser.org/
public void delete1(String table,String COLUMN,String link) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%");
}
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, "PRODUCTNAME" + "LIKE ?", new String[]{name+"%"}) ;
}
Could you tell me how to do it or how have i to correct code ?
using db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{name+"%"}) ; will only delete rows that start with the value in name.
Perhpas you want :-
db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) ;
Then it would delete rows that contain the value rather than start with the value.
With db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%"); you need to enclose the string in single quotes and assuming that you want to delete a row that contains the value then use :-
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE '%"+link+"%'");
Using the delete convenience method (the first part) is the better option as it protects against SQL Injection, it properly encloses the value, builds the underlying SQL and also returns the number of affected (deleted) rows.
If you use the following, this will write dome debugging information that may assist in debugging :-
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEINFO","Attempting to delete rows with \n\t->" + name);
int deletedCount = db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) >0) ;
Log.d("DELETEINFO","Deleted " + deletedCount + " rows.");
}
I was trying to duplicate this SQLite statement from the line of code below:
Cursor cursor = db.rawQuery("update tbl_details SET ticket = replace(ticket, " + tempID + ", " + ticket + ")", null);
to this one:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ticket", "replace(ticket, " + tempID + ", " + ticket + ")");
db.update("tbl_details", cv, null, null);
return true;
What I am trying to do is to get a New ID and replace all instances of the old temporary ID in the database. But the code above is changing all the records in ticket column.
Please help. Thank you!
You can use ContentValues to bind literal values only, not expressions like replace(...).
To run the raw UPDATE SQL, just use execSQL() instead of rawQuery(). rawQuery() alone won't actually run the code until the returned Cursor is moved.
I wrote the following code to insert some records into table from the table of another database.
But I'm unable to, even after executing a sql statement it shows that there are no records in the table.
public int copy_to_all_source_table(String dbpath,String backpath)
{
SQLiteDatabase db1 = this.getWritableDatabase();
//Opening App database(i.e. dbpath) and attaching it as "OLD"
db1.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_old="ATTACH '"+ dbpath +"' AS OLD";
db1.execSQL(attach_old);
//Opening New File which is Student.db(i.e. dbpath) and attaching it as "NEW"
db1.openDatabase(backpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_new="ATTACH '"+ backpath +"' AS NEW";
db1.execSQL(attach_new);
// Getting count of records in table of "NEW"
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor new_data = db1.rawQuery(new_query, null);
Integer new_count= new_data.getCount();
//INSERTING ALL RECORDS FROM TABLE OF NEW TO TABLE OF OLD
String insert_query ="INSERT INTO 'OLD'.'"+ TABLE_CONTACTS +"' SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor success_insert = db1.rawQuery(insert_query, null);
// Getting count of records in table of "NEW"
String after_insert_old_query =" SELECT * FROM 'OLD'.'"+ TABLE_CONTACTS +"'";
Cursor old_data = db1.rawQuery(after_insert_old_query, null);
Integer old_count= old_data.getCount();
}
RESULT:
new_count = 11
old_count = 0
So, no record has been inserted.
You are using rawQuery() to execute an INSERT command. Which will never work.
Use execSQL(), instead
Moreover, the last comment is misleading, because it says you want the count from the NEW table, but you are counting from the OLD one.
And, please, get rid of the string delimiter characters (').
I.e.:
this
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
should be
String new_query = "SELECT * FROM NEW." + TABLE_CONTACTS;
I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();
I want to write a Query to delete a row from the table. I am confused of writing the statement. I need some help in writing this. I am providing my requirement here with plain sql statement.
(Pseudo code)
delete from tablename where value =="string1" && value2 == "string2" && value3 == "string3";
I want to write this in the Sqlite syntax for android db.delete(tablename, whereclause, whereargs);.
I would be thankful for your help.
a better way would be to use
String where = "value1 = ?"
+ " AND value2 = ?"
+ " AND value3 = ?";
String[] whereArgs = {string1,string2,string3};
String table_name = "myTable";
String where = "value1 = 'string1'"
+ " AND value2 = 'string2'"
+ " AND value3 = 'string3'";
String whereArgs = null;
mDb.delete(table_name, where, whereArgs);
mdb.delete("tablename",new String("value1=? and Value2=? and value3=?"),new String[]{value1,value2,value3});
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tablename WHERE value1='"+string1+"' AND value2='"+string2+"' AND value3='"+string3+"' "); //delete row in a table with the condition
db.close();