SQLite query - date reserved word? - java

Am just curious, is date a reserved word i SQLite? I have a column which is named date, and trying to run this query:
DELETE FROM cases WHERE date <= date('now','-1 day')
By doing this:
String query = "DELETE FROM cases WHERE date <= date('now','-1 day')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
But the cursor just gives me a false back, when calling moveToFirst. But in my database there are actually rows that are older than one day. Can anybody explain whats wrong here?
Thanks!

Yes it seems to be a reserved word.
look at: http://www.sqlite.org/lang_datefunc.html
date(timestring, modifier, modifier, ...)
It's strange to have a cursors form DELETE statement. Try to split the operation in
SELECT * FROM cases WHERE date <= date('now','-1 day')
then execute your checks
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
and then execute the DELETE part
DELETE FROM cases WHERE date <= date('now','-1 day')

This question is quite old but it deserves a proper answer.
No, date is not a reserved word.
The problem with your code is that you are using the method rawQuery() to delete from the table, which is not the way to do it.
rawQuery() should be used to return rows from the table in the form of a Cursor object.
Since your sql statement does not return any rows the method moveToFirst() returns false.
What you should use is the method delete() which returns the number of deleted rows:
int result = db.delete("cases", "date <= date('now', '-1 day')", null);

Related

trying to call user_id from sqlite

I'm trying to call user_id from sqlite database but I get this error
android.database.sqlite.SQLiteException: unknown error (code 0 SQLITE_OK): Queries can be performed using SQLiteDatabase query or rawQuery methods only.
at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
public Database user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT user_id FROM OrderDetails ;");
db.execSQL(query);
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
c.moveToFirst();
}
return user_id();
}
Please don't recommend another solution because I'm stuck with this for more than a day and I tried almost all solutions represented in stackoverflow and online
From: https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#execSQL(java.lang.String)
public void execSQL (String sql) Execute a single SQL statement
that is NOT a SELECT or any other SQL statement that returns
data.
So remove this line:
db.execSQL(query);
The method execSQL() is not used to execute queries that fetch rows, like SELECT statements. You can use it with INSERT, UPDATE, CREATE, etc.
Also, I think that you want to return the user's ids as a Cursor, right?
So why:
public Database user_id()
this returns a Database object (whatever this is).
Change the method to this:
public Cursor user_id(){
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT user_id FROM OrderDetails";
Cursor c = db.rawQuery(query, null);
return c;
}

How to use prepared statement for sql?

I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0

Cursor is empty but query is (supposedly) right

I've got very strange problem.
My snippet is looking like that
public Wynik getData(int pomiar, int godzina) {
Wynik wynik = null;
String query = "SELECT * FROM " + "insulina" + " WHERE godzina = " + godzina +
" AND cukier = " + pomiar;
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, null)) {
Log.i("tag", "cursor length:" + cursor.getCount());
if (cursor.getCount() > 0) {
String s = DatabaseUtils.dumpCursorToString(cursor);
Log.d("s", s);
cursor.moveToFirst();
wynik = new Wynik
(cursor.getInt(cursor.getColumnIndexOrThrow("godzina")),
cursor.getString(cursor.getColumnIndexOrThrow("insulina")),
cursor.getInt(cursor.getColumnIndexOrThrow("dawka")),
cursor.getString(cursor.getColumnIndexOrThrow("cialo")));
}
cursor.close();
return wynik;
(sorry for not English convention, but it was meant to be quick, routinely project)
Whole app idea is to help my friend with his grandmother's diabetes. He would insert an result of blood sugar level test (cukier) and time of test is checked automatically (godzina).
Based on those, app should return a whole result (wynik), with required dose of insulin (dawka), type of it (insulina) and part of body from which the blood should be taken (cialo).
Database looks like this:
So for example. The blood result is 10 (it's only thing which user is inserting) and it's 7 P.M (19, by 24-hours convention - the program is giving the closest hour of test, so it's 18). So, the query looks like
SELECT * FROM insulina WHERE godzina = 18 AND cukier = 10
And here's my problem. The app is recognizing cursor length as 0 (it should be 1) even if my other app related to database creation (DB Browser for SQLite) is giving out my result properly with the same query
Also Android Studio says that database is sucessfully opened.
I cannot find a fault here. And I'm really confused with this problem.
I think the query should be :
String query = "SELECT * FROM insulina WHERE godzina = ? AND cukier = ?";
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(godzina), String.valueOf(pomiar)})) {
//... rest of code
Also looks like you're using "try with resources" so the close isn't explicitly necessary.

cursor.getCount() returning 1 but should have returned 0

I have a query which is
SELECT SUM(amount) AS total FROM transactions WHERE transaction_date > 1477333800
For this query, cursor.getCount() is returning 1. But when iterating through the cursor, the value is coming up null.
public Cursor getTotalForToday(long start)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(amount) AS total FROM "+TRANSACTION_TABLE+" WHERE transaction_date > "+start, null);
return c;
}
Cursor cursor = db.getTotalForToday();
if(cursor.getCount() == 0) // this is evaluating to false
{
forToday.setText("Zero"); //forToday is TextView
}
else
{
while(cursor.moveToNext())
{
String total_today = cursor.getString(0); // this is returning null
forToday.setText(total_today);
}
}
PS: The data type of amount is integer in the table
If I query the same thing in SQLLite Firefox extension, I'm getting the following output
Ideally, the number of rows returned should have been 0, but I have no idea why it is returning as 1.
Here is the data in the table btw:
Aggregate SQL functions such as SUM() always return a result row. The result itself can be null.

Update multiple rows in Android sqlite

I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question

Categories