In my app, when the activity is destroyed, I want to update a column value to 0. For that I have written the query, but it seems not to be working for me, because when ever I start the app I get the same old values.
Code
public void resetSelectOptions() {
database = DatabaseManager.getInstance().openDatabase();
String query = "Update " + TableName + " SET " + Selected_Option + "=0";
try {
database.rawQuery(query, null);
}
catch (SQLiteException e) {
}
DatabaseManager.getInstance().closeDatabase();
}
How can I fix this problem?
Use this method to updating the rows,database.update() and
rawQuery is used to select query.
rawQuery() only executes queries (SELECT).
For any other SQL command, use execSQL().
So, simply convert this
database.rawQuery(query, null);
to this
database.execSQL(query, null);
It is not correct that the rawQuery() method executes only SELECT queries, it doesn't, but it is unnecessary to use it for an update, because you don't have any result - what to be iterated with the result Cursor at the ends, so try to use the execSQL() method. For more information take a look at this SO question android.database.sqlite.SQLiteDatabase.rawQuery() is not updating a DATETIME column with a SQLite datetime() function
Related
I've spent the whole day so far trying to get a select query to execute viarawquery or query, but I've had no luck so far.
The select statement I want to run is as the following:
SELECT * FROM h_word WHERE category='GRE' AND DONE=0 ORDER BY RANDOM() LIMIT 1
category is a TEXT type column and DONE is an INTEGER type with the default value of 0.
While the query works fine when executed directly in SQLite, in android,it doesn't return any results.
I've tried the below with no luck (the method is located in a class extended from SQLiteAssetHelper which itself is a helper class originally extended from SQLiteOpenHelper originaly taken from here: https://github.com/jgilfelt/android-sqlite-asset-helper:
public Cursor getRandomWord() {
Cursor c;
SQLiteDatabase db = getWritableDatabase();
c=db.rawQuery(query, null);
String query = "SELECT * FROM h_word WHERE category='GRE' AND DONE='0'
ORDER BY RANDOM() LIMIT 1 ";
c=db.rawQuery(query, new String[] {});
c.moveToFirst();
db.close();
return c;
}
I also tested with GRE instead of 'GRE' and 0 instead of '0' but it made no difference.
did the following as well:
public Cursor getRandomWord() {
Cursor c;
SQLiteDatabase db = getReadableDatabase();
c=db.query(true, "h_word", new String[] {
"_id",
"word",
"english_meaning"
},
"category" + "=?" + " AND " +
"DONE" + "=?",
new String[]{"GRE" ,"0"},
null, null, "RANDOM() LIMIT 1" , null);
c.moveToFirst();
db.close();
return c;
}
but the cursor remains empty.
Any ideas what I might be doing wrong here?
Any help would be much appreciated.
PS: when running a simple select statement without a where clause it, works fine.
After another few hours of struggling, I figured it's a bug in android's SQLiteDatabase class.
I managed to solve the problem by changing the name of the "category" column to something else.
Seems like "category" is a key word in the android SQLiteDatabase code, and makes a query return nothing when written in where clauses on the android side.
Someone else also had this problem here:
Android rawquery with dynamic Where clause
My Java code Update Data base Table
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+code;
Log.d("Qry", qq);
myDbHelper.updatequery(qq);
updatequery method
public void updatequery(String qry)
{
Cursor c = myDataBase.rawQuery(qry, null);
Log.d("Up", ""+c.getCount());
}
When i updated Data base the count return 0 and table not updated
I am using this Also but not work
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+"'"+code+"'";
Please Help Me how i can fix this problem
Thanks In Advance
Use execSQL() for such SQL and not rawQuery().
rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program.
execSQL() both compiles and runs the SQL program.
There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe.
To update sqlite query change
Cursor c = myDataBase.rawQuery(qry, null);
to this
myDataBase.execSQL(qry);
try to use this:
ContentValues values = new ContentValues();
values.put("Recieve", str);
db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });
This is my method to delete a row from the database where appointment_date is equal to a date that was passed in
public void deleteAllAppointments(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteAllQuery = "DELETE FROM " + TABLE_APPOINTMENTS + " WHERE appointment_date = '" + date + "'";
db.rawQuery(deleteAllQuery, null);
Log.d("Query: ", deleteAllQuery);
}
I then use it like this
//Database (DatabaseHandler is the one that contains all database methods)
final DatabaseHandler database = new DatabaseHandler(this);
//This happens when button is clicked, it is tested an executes with every chick,
//#param selectedDate is a string like "18/03/2014"
database.deleteAllAppointments(selectedDate);
It executes and query looks like this
DELETE FROM appointments WHERE appointment_date = '18/03/2014'
However row with appointment_date = '18/03/2014' is not deleted.
I'm sure database is set up correctly as I have working methods with it and all information is received from there in correct format.
NOTE: Adding "*" to "DELETE * FROM..." returns a fatal syntax error.
rawQuery() just compiles the SQL but does not run it. To actually run it, use either execSQL() or call one of the moveTo...() methods on the cursor returned by rawQuery().
For further info, see What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?
For tasks such as insert or delete there are really great "convenience methods" like the [delete method](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])) already built in to the database.
public int delete (String table, String whereClause, String[] whereArgs)
As to why your current approach would fail, it could be something as simple the format of the column you're trying to delete not matching (e.g. you have created the table as a date value and not a string).
In any case, using the built in delete method is easier because it will notify you when it fails by returning the number of rows affected by the delete. rawQuery just returns a cursor, which you would then have to get the result from to see if it worked.
Are you sure your data value is in European format of day/month/year ala your query value of 18/03/2014 and maybe its not US style of month/day/year: 03/18/2014.
Not trying to be US-centric but that was my first thought.
Otherwise, definitely look at SQLiteDatabase.delete:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])
I have a static sqlite database in Android. A function takes a int type of input and makes a query to the database. It's working fine upto input values of 97,500, but if I enter anything larger then one of two cases happens
If input is 98,000-99,500 it returns null
If input greater than 100,000 it returns the wrong data
Here's the function that's malfunctioning:
Budget getBudget(int income,String name)
{
Budget B=null;
Log.d("DB", String.valueOf(income));
try{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT * FROM "+BudgetTable+" WHERE "+Low+"<=? AND "+High+">=?", new String[]{String.valueOf(income),String.valueOf(income)});
Log.d("DB", String.valueOf(cur.getCount()));
if(cur.getCount()!=0)
{
Log.d("DB", "Cursor not empty");
cur.moveToFirst();
B=new Budget(0, income,cur.getInt(cur.getColumnIndex(MortgageRent)),cur.getInt(cur.getColumnIndex(Utilities)) ,
cur.getInt(cur.getColumnIndex(LightnPower)), cur.getInt(cur.getColumnIndex(PhonenInternet)),
cur.getInt(cur.getColumnIndex(HomeMaintenance)), cur.getInt(cur.getColumnIndex(HomeCleaning)),
cur.getInt(cur.getColumnIndex(Groceries)), cur.getInt(cur.getColumnIndex(Clothing)),0,
cur.getInt(cur.getColumnIndex(PersonalGrooming)), cur.getInt(cur.getColumnIndex(MedicalnPharmacy)),
cur.getInt(cur.getColumnIndex(HealthInsurance)), cur.getInt(cur.getColumnIndex(LifeInsurance)),
cur.getInt(cur.getColumnIndex(HomeInsurance)), cur.getInt(cur.getColumnIndex(Accounting)),
cur.getInt(cur.getColumnIndex(BankFees)), cur.getInt(cur.getColumnIndex(Fuel)),
cur.getInt(cur.getColumnIndex(ServicenRepairs)), cur.getInt(cur.getColumnIndex(GovernmentCharges)),
cur.getInt(cur.getColumnIndex(CarInsurance)),0, cur.getInt(cur.getColumnIndex(PublicTransport)),
cur.getInt(cur.getColumnIndex(Entertainment)), cur.getInt(cur.getColumnIndex(SportsnGym)),
cur.getInt(cur.getColumnIndex(EatOut)), cur.getInt(cur.getColumnIndex(Alcohol)),
cur.getInt(cur.getColumnIndex(Gifts)), cur.getInt(cur.getColumnIndex(Holidays)),
cur.getInt(cur.getColumnIndex(NewspapernMagazine)), cur.getInt(cur.getColumnIndex(Others)), 0, 0, name);
Log.d("DB", String.valueOf(cur.getInt(cur.getColumnIndex(IncomeLevel))));
cur.close();
db.close();
}
}catch(Exception ex)
{
Log.d("DB", ex.getMessage());
}
return B;
}
Below is a screenshot of the data in database...I can't figure out why it doesn't work.
As I can't see your database, I am led to believe the source of your problem is this line:
Cursor cur=db.rawQuery("SELECT * FROM "+BudgetTable+" WHERE "+Low+"<=? AND "+High+">=?", new String[]{String.valueOf(income),String.valueOf(income)});
specifically the fact that you are using income for both greater-equal than AND less than-equal. Are you sure this is what you want? Are you sure it is not cuppose to be
Cursor cur=db.rawQuery("SELECT * FROM "+BudgetTable+" WHERE "+Low+"<=? AND "+High+">=?", new String[]{String.valueOf(lowIncome),String.valueOf(highIncome)});
You shouldn't pass numbers as strings, because strings have different rules of comparison, for example, the string "2000" will be considered greater than the string "102500".
They warn about it in the javadoc documentation:
selectionArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Your should rewrite your query like this:
Cursor cur=db.rawQuery("SELECT * FROM "+BudgetTable+
" WHERE "+Low+"<=" + income + " AND "+High+">=" + income);
Also, it is quite a common issue and some people encountered a similar problem: SQLite rawQuery selectionArgs and Integers Fields
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);
...
}