I have an idless database in my application. How can I delete any of the rows? My database code is as follows:
mydb=Nickname.this.openOrCreateDatabase("private", 0, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS numbers(nickname varchar,number INT(13))");
Anyone know how it is possible?
mydb=Clear.this.openOrCreateDatabase("private", 0, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS numbers(_id INTEGER PRIMARY KEY,nickname varchar,number INT(13))");
mydb.execSQL("DELETE FROM numbers WHERE id='=?' AND number='"+num+"'");
//num is string which contains which number i wish to delete
The SQLDatabase object has a delete method. public int delete (String table, String whereClause, String[] whereArgs)
mydb.delete(TABLE, "nickname = "+ DatabaseUtils.sqlEscapeString(name), null);
mydb.execSQL("DELETE FROM your_db.your_table WHERE <write your SQL conditions here> ");
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 have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.
Please suggest me a method to delete all tables from the database.
This is the code that I used:
public void deleteall(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
do
{
db.delete(c.getString(0),null,null);
}while (c.moveToNext());
}
function deleteall() is called on button click whos code is given as below:
public void ButtonClick(View view)
{
String Button_text;
Button_text = ((Button) view).getText().toString();
if(Button_text.equals("Delete Database"))
{
DatabaseHelper a = new DatabaseHelper(this);
a.deleteall();
Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
}}
Use DROP TABLE:
// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
Tim Biegeleisen's answer almost worked for me, but because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I shouldn't drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
delete database instead of deleting tables and then create new with same name if you need. use following code
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
For me, the working solution is:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}
this is my code :
SQLiteDatabase.loadLibs(this);
File databaseFile = getDatabasePath("db");
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "Ab61", null);
database.execSQL("drop table comments");
database.execSQL("CREATE TABLE IF NOT EXISTS comments(_id INTEGER PRIMARY KEY,spot_id INTEGER,server_id INTEGER" +
",description TEXT,uid TEXT ,dates TEXT,name TEXT)");
database.execSQL("insert into comments values (null, 34, 3, 'asdasd', 'asdsad', 'asda', 'asds');");
Cursor ss=db.rawQuery("SELECT * from comments", null);
Log.v("this",Integer.toString(ss.getCount()));
I've db database ,it's an sqlite database . this is a test code so , I remove the whole database ,create it again and insert a new row .
It doesn't get any error .
the cursor getCount return 0 , it means there is nothing added to database .
It driving me crazy :(
could you help me ?
You are inserting the data into a different database (database) than that which you are querying (db).
private void InitializeSQLCipher(){
try {
SQLiteDatabase.loadLibs(getApplicationContext());
}
catch (Exception e) {
e.printStackTrace();
}
File databaseFile = getDatabasePath("demo.db");
databaseFile.mkdirs();
databaseFile.delete();
database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
database.execSQL("create table t1(a, b)");
database.execSQL("insert into t1(a, b) values(?, ?)", new Object[]{"one for the money","two for the show"});
}
Cursor c = null;
c = database.rawQuery("SELECT a,b from t1", null);
if (c != null){
if(c.moveToFirst()){
while(!c.isAfterLast()){
//Log.e("xlcx", c.getString(c.getColumnIndex("a")));
Log.d("xlcx", c.getString(c.getColumnIndex("b")));
c.moveToNext();
}
}
}
please refer
http://androidjug.blogspot.in/2014/07/sqlcipher-for-android-application.html
Normally I can use the following code to delete a recod.
SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
db.execSQL("CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
db.delete("person", "id = ?", new String[]{"35"});
Now I hope to delete some records, the sql just like
delete from test.db where id in ('6','4')
How can I write the code?
Is db.delete("person", "id in ?", new String[]{'6','4'} ) right?
public int delete (String table, String whereClause, String[] whereArgs)
delete method description is quite clear. If you want to delete a row of the given id then it should be something like this:
db.delete("person", "id="+String.valueOf(int_id_to_delete), null);
Futher, if you want to delete multiple rows at once use the following:
db.delete("person", "id"+"=?", new String[]{"6","4"});
You can use the following code or can execute a raw query as android permits.
db.delete("person", "id"+ "=?", new String[] {"4","6"});
This is my table apTable:
db.execSQL("CREATE TABLE "+apTable+"
("
+idAP+" TEXT PRIMARY KEY , "
+ssID+" TEXT, "
+testAPid+" INTEGER NOT NULL ,FOREIGN KEY ("+testAPid+") REFERENCES "+testsTable+" ("+colTestID+") ON DELETE CASCADE);");
I want to make a query that will give me the idAP rows where, idAP equals a given value and where the foreign key equals another given value.
I'm doing it like this, but it isn't working:
public String CheckAP(String BSSID, String Teste)
{
SQLiteDatabase db=this.getReadableDatabase();
String[] params=new String[]{BSSID, Teste};
Cursor c=db.rawQuery("SELECT "+idAP+" FROM "+apTable+" WHERE "+idAP+"="+BSSID+" AND "+testAPid+"="+Teste, null);
c.moveToFirst();
int index= c.getColumnIndex(idAP);
return c.getString(index);
}
What is the problem here?
Refer to this.
Use a database openhelper.
http://www.screaming-penguin.com/node/7742
And use this to check if you have created your database.
http://androidblogger.blogspot.com/2009/06/tutorial-how-to-access-android-database.html
try this? think the built-in query works just without having to put in the where clause
Cursor c=db.query(apTable, idAP, idAP+"="+BSSID+" AND "+testAPid+"="+Teste, null, null, null, null);
but why would you want to select idAP if you already know you are selecting a specific idAP? shouldnt you be doing something like this?
Cursor c=db.query(apTable, idAP, testAPid+"="+Teste, null, null, null, null);
:S