Delete SQLite row with multiple WHERE arguments in Android - android

I would like to delete a record in the database with multiple WHERE arguments.
My database helper class has this method:
public void deleteManualRow(String where){
try {db.delete(TABLE_NAME_MANUAL, where, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
The "where" string which is passed to this method is seen as this through the debugger:
eventName='Manual Event 6' AND eventStartTime='2011-07-18T05:40:00.000-0400' AND eventEndTime='2011-07-18T06:40:00.000-0400'
How am I supposed to structure this WHERE clause if I want to delete a record with multiple arguments for WHERE? All of the datatypes are strings.

like this db.delete(TABLE_NAME_MANUAL,"Column1='5' and column2 like '3'", null);

You have to learn your sqlite api, next I show from Android flutter example.
From sqlite_api.dart:
Future<int> delete(String table, {String where, List<dynamic> whereArgs});
So your result code will be:
await db.delete(tableName, where: 'place_id = ? and country_id = ?', whereArgs: [place_id, country_id]);

Related

make sure cursor is initialized correctly before accessing data from it

Can anyone help me how to execute this query?
I am trying to fetch distinct supervisor from project table. supervisor is column name and its index is 5.
try {
String query = "select distinct supervisor from project ";
Cursor cursor= db.rawQuery(query,null);//query( query , null, null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(5));
} while (cursor.moveToNext());
}
// finish();
cursor.close();
db.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return labels;
}
Your query is wrong.
You have to query write like this.
select * from project where YOUR_CONDITION
I don't know what you exactly trying to do.
Example query.
select * from customers where LastName = 'Tremblay'
To get Distinct value of supervisor you should query like this.
select * from project group by supervisor
Hope it helps:)
You could use an if statement ie if cursor != null, do something.

cursor return column names instead of values

I want to fetch data from table "student" in SQLite android database
and here is the method that I use to retrieve the data
public Cursor getAllStudent(){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={"_id",
"'reg_number'",
"'School_id'",
"'class_id'",
"'first_name'",
"'last_name'",
"'PPN'",
"'photo'",
"'CyncStatus'"};
Cursor cursor=null;
try {
cursor = db.query("student",columns,null, null,null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("select student failed: %d", e.toString());
}
return cursor;
}
and this is how I iterate through the result
Cursor c1 = studentHelperAdapter.getAllStudent();
c1.moveToFirst();
while (!c1.isAfterLast()){
String reg = c1.getString(1); // return column name not value
String name = c1.getString(4); //return name column not value
String reg = c1.getString(5); //return name column not value
c1.moveToNext();
}
c1.close();
and I have tried to add this line below to see cursor content and I realized that no data was fetched there are only column names
Log.d("AB cursor ",android.database.DatabaseUtils.dumpCursorToString(c1));
Anyway, there 2 similar questions but none of the solutions solved my problem
Get the field value with a Cursor
How to get field value instead of column name?
I look forward to see your answer here, thanks
I think your column names should just be strings.
"reg_number" not "'reg_number'"
also make sure that you are using correct types. Is the value stored in column "reg_number" really a String?

Delete Record from Database row wise in Android

I'm trying to build my first Android application, but I'm experiencing a problem: I write following code for insert record in database, but I don't know how to delete a row, so can anybody help me???
Code for insert record:
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Student emp=new Student(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of students "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
DELETE FROM tableName WHERE fieldName = value
This is delete query. Execute it with execSql
Edit: use execSql instead of rawQuery
You can simply do this using SQLiteDatabase.execSQL() and don't try rawQuery It's meant for querying.
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tableName where fieldName=Value");
db.close();
Check out the detailed answer here

Android SQLite rawQuery giving trouble

There's this method which i've created to know if a contact exists in my Sqlite database.
public Cursor doesContactExist(String name)
{
return db.rawQuery("select * from contacts where name = ?; ", new String[] {name});
}
But whenever it is called from another activity it crashes only at this point....
if(db.doesContactExist(name)==null){ <== crashes here
try {
db.open();
db.insertContact(name,cNumber);//name and number are Strings
listItems.add(name); //a List View array
db.close();
adapter.notifyDataSetChanged(); //adapter for ListView
}
catch (Exception e) {
//some code }
}
According to me the rawQuery is having some troulble, especially the sql String in it.
Any help please?
you try to make a select before your database is open:
if(db.doesContactExist(name)==null){ <== it is closed here
try {
db.open(); <== open the db here
change it to:
db.open();
if(db.doesContactExist(name)==null){
try {
I think it might help you..
db.open();
if(db.doesContactExist(name)==null)
{
try
{
// Your Code Here..
}
}
and in Database Class
public Cursor doesContactExist(String name)
{
return db.rawQuery("SELECT * FROM contacts WHERE name=?", new String[ {name.toString()});
}
use db.open() method before using any database function because it will open your connection with database.. and at last don't forget to close database like db.close() and if you are using Cursor anywhere in code please close this also. it not generates any error but it gives you warnings. :)

Get insert error code on sqlite

How can i run a sql statement on a sqlite database (in android) and get the result of the query? I need to know for sure if the query was executed or not.
I came up with :
db.execSQL(sql);
but this is a void function.
I get the query_string from a database so i don't know is is a insert or update or delete statement. I know for sure that it will not be a select statement.
Try something like this:
public String insertQuery(String sql) {
try{
db.execSQL(sql);
}
catch (SQLException ex){
return ex.toString();
}
return null;
}
If you are using SQLiteDatabase, you can do two things:
1.) *Query without result (UPDATE, DELETE, DROP, ALTER etc...)*
These queries doesn't return any value, they modify the database. The function to do this is called execSQL(String). You can simply give it an SQL query in string format, and it will execute it.
2.) *Query with a result (SELECT)*
These queries will return a Cursor object. With a cursor you can iterate on a result set, like you would with any other iterator. The cursor will always 'contain' a single row from the actual resultset, and you can call the move functions to step forward/backward. The function to do this is called rawQuery(String, String []). You can also use the query() function, using this, you have to type less SQL.
An example:
Cursor cursor = database.rawQuery("SELECT * FROM yourtable", null);
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
/*this means you want to get from the current row a String
(CHAR, VARCHAR or TEXT) value from the 0th (first) column*/
String str = cursor.getString(0);
/*This means, that you want to get from the current row an
integer value from the 1st (second) column*/
int i = cursor.getInt(1);
...
}

Categories

Resources