I store date as TEXT in my database in this format YYYY-MM-DD.
Each row has start date and final date.
I want to select the row that today date is between the start date and final date.
Today date is string and is in the same format as those ex.2014-07-29
I've tried
SELECT * FROM TABLE_NAME WHERE date(todayDate) BETWEEN date(COLUMN_START_DATE) AND date(COLUMN_FINAL_DATE)
but it didn't work. I get 0 row.
I've also tried
SELECT * FROM TABLE_NAME WHERE strftime('%Y-%m-%d', todayDate) BETWEEN COLUMN_START_DATE AND COLUMN_FINAL_DATE
Still not work.
What am I doing wrong?
use this to get the results:-
String selection = "from_duration<=Datetime('" + initial_date
+ "') AND to_duration>=Datetime('" + final_date + "')";
your_database.query(Table_Name,Columns_youwant, selection,
null, null, null, null);
Related
I want to compare current month data(expenses) with previous month data(expenses) which is store in database datewise. kindly some one guide me please.
I write this command for current month data but did not work for me.
Cursor
cursor= database.rawQuery("
SELECT amount
FROM Groceryitems
WHERE Strftime('%Y-%m', 'now')
", new String[]{});
There must be a date column in the table Groceryitems and this column you must check if it contains a date of the current month:
String sql = "SELECT amount FROM Groceryitems WHERE strftime('%Y-%m', datecolumn) = strftime('%Y-%m', 'now')";
cursor= database.rawQuery(sql, null);
Change datecolumn with the name of the date column in the table.
To get the previous month's data:
String sql = "SELECT amount FROM Groceryitems WHERE strftime('%Y-%m', datecolumn) = strftime('%Y-%m', 'now', '-1 month')";
cursor= database.rawQuery(sql, null);
I am saving the data with the date it was filed, but the date I inset changes to the current date
When you save the data
Calendar currentDate=Calendar.getInstance();
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, done_today1 + "\n" + done_today2 + "\n" + done_today3, thankful_for1 + "\n" + thankful_for2 + "\n" + thankful_for3 + "\n" + thankful_for4 + "\n" + thankful_for5, for_relationship, for_kids, for_business, currentDate.get(Calendar.DATE) + "-" + currentDate.get(Calendar.MONTH) + "-" + currentDate.get(Calendar.YEAR));
Inserts the data into the table
public void putInformation(DatabaseOperations dop,String happenedToday,String thankfulFor,String forRelationship,String forKids,String forBusiness,String currentDate){
SQLiteDatabase SQ=dop.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(TableData.TableInfo.DONE_TODAY, happenedToday);
cv.put(TableData.TableInfo.THANKFUL_FOR,thankfulFor);
cv.put(TableData.TableInfo.FOR_RELATIONSHIP,forRelationship);
cv.put(TableData.TableInfo.FOR_KIDS,forKids);
cv.put(TableData.TableInfo.FOR_BUSINESS,forBusiness);
cv.put(TableData.TableInfo.CURRENT_DATE,currentDate);
SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Database operations", "One Row Inserted");
And when I retrieve the date this way
Cursor CR = dop.getInformation(dop);
CR.moveToFirst();
Toast.makeText(DisplayTable.this,""+CR.getString(5),Toast.LENGTH_LONG).show();
I am getting the current date and not the date that the data was filed in.
Any one knows why is it happening?
In SQL, CURRENT_DATE is a keyword that refers to the current date.
To access a column with the same name, you have to quote the column name (double quotes are for identifiers; single quotes are for strings):
> CREATE TABLE t(current_date);
> INSERT INTO t VALUES('x');
> SELECT current_date FROM t;
2015-09-28
> SELECT "current_date" FROM t;
x
> SELECT 'current_date' FROM t;
current_date
It might be a better idea to use a different column name.
Best way to handle date and times is to always use ISO standard timestamps, the ones with T and Z. This makes translating actual dates within different time zones easy.
One way also is saving date and times using unix timestamp, its a long integer that can be translated to the actual dates of different time zones, so it will reflect always the correct time based on your time zone.
I want to delete some records from android's database where two conditions are fulfilled.
1. there's a column with the name as sync_status, it should have a value 'C' and
2. there's column which has date.
Now I want to delete only those rows where sync_status is = 'c' and date is less than device's current date. I'm having problem in comparing the device's current date with the date stored in the database and my function deletes all the records.
public int RemoveSyncData(){
DBHelper = new DatabaseHelper(context);
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy ");
Calendar calObj = Calendar.getInstance();
String currentDate = dateFormat.format(calObj.getTime());
Log.e("current date",currentDate);
int rows = db.delete(DATABASE_TABLE_DAILY_ATTENDANCE, KEY_ATTENDANCE_SYN_STATUS + "= ? and " + KEY_ATTENDANCE_DATE_ONLY + " != '" + currentDate + "'", new String[] {"C"});
db.close();
return rows;
}
If you absolutely want to keep the date as a string in the form MM-DD-YYYY in your database column, then the only way to do comparison of those dates is to convert them to seconds using SQLite's strftime function. However, in order to do that, you have to restructure the date as YYYY-MM-DD because your current format is not one that can be used as input to the date and time functions of SQLite.
Here is a sample:
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Calendar calObj = Calendar.getInstance();
String currentDate = dateFormat.format(calObj.getTime());
String where = KEY_ATTENDANCE_SYN_STATUS + " = ?1 AND "
+ "STRFTIME('%s', SUBSTR(" + KEY_ATTENDANCE_DATE_ONLY + ",7) "
+ "|| '-' || SUBSTR(" + KEY_ATTENDANCE_DATE_ONLY + ",1,5)) < "
+ "STRFTIME('%s', SUBSTR(?2,7) || '-' || SUBSTR(?2,1,5))";
String[] whereArgs = {"C", currentDate};
int rows = db.delete(DATABASE_TABLE_DAILY_ATTENDANCE, where, whereArgs);
If you use yyyy-MM-dd when creating currentDate, you can replace the second instance of the ugly substring + concatenation with just STRFTIME('%s', ?2), but you will still need the first substring + concatenation to transform the column values in the table.
If it's not too late for you to change how your database stores the date, make your life easier by either storing as yyyy-MM-dd (to get rid of all the substring + concatenation above), or better yet store the long date and only worry about converting it to and from MM-dd-yyyy at the java layer.
** EDIT **
Your condition is right it should delete only the rows that meet the condition, just tested it on my SQLite Viewer with some dummy data..
Just be 100% sure that your variable names match the column names and also check the database, if there are some rows which shouldn't be deleted. Maybe there is no entry for today's date and "C" is present in all rows thats why all the records are being deleted.
You can also try the "not so good way":
db.execSQL("delete FROM tableName WHERE KEY_ATTENDANCE_SYN_STATUS = 'C' AND KEY_ATTENDANCE_DATE_ONLY != '"+currentDate+"'");
The above is not a good way as execSQL won't return anything so you won't have anyway to know if it was successful except for checking it yourself.
The above approach is only to test your condition though.
I have dates stored in a SQLite table in int format (i.e. milliseconds - derived from System.currentTimeMillis()). I now want to query all rows from the table where the date is equal to today's date, but the query below always returns zero, even though file_uploaded_date in the upload_history table is set to today's date in at least 20 rows.
Can anyone tell me what's wrong with my query?
String today = new SimpleDateFormat("d-MMMM-yyyy").format(new Date());
String sql = "SELECT COUNT(*) as uploaded_today from upload_history "
+ "WHERE strftime('%-d-%b-%Y',file_uploaded_date) = strftime('%-d-%b-%Y','" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
int uploadedToday = cursor.getInt(cursor.getColumnIndex("uploaded_today"));
}
I'd say you have your format-strings incorrect.
I don't see a %b argument in the documentation. For month, you would want to use %m. Also %-d doesn't seem right. Use the following format string instead: %Y%m%d.
Further, you are then passing a poorly-formatted string into the query, rather than the int, and relying an sqlite to correct that. Instead, compare to a SimpleDateFormat( "yyyyMMdd" ) without further conversion.
Your code would then look like this:
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String sql = "SELECT COUNT(*) from upload_history "
+ "WHERE strftime('%Y%m%d',file_uploaded_date) = '" + today + "')";
Cursor cursor = db.rawQuery(sql, null);
if(cursor != null && cursor.moveToFirst()){
int uploadedToday = cursor.getInt(0);
}
(Note that if you return only one column, you don't have to name it, and can just access the first column for the result.)
Further, please be aware that this query will cause a table-scan every time it's executed, as sqlite needs to convert all the epochs to strings. You'd be better off adding a date column to the table, and update it once:
UPDATE upload_history
SET just_the_date = strftime('%Y%m%d',file_uploaded_date)
This will then allow you to do much quicker searches, and even search by year or month, using the LIKE operator. If your table is very large, you might want to put an index on that column as well.
You can add date in db as a string in date format like yyyy-mm-dd hh-mm-ss and compare the same while retrieving it from database using sql query.
I am writing an android application storing workout dates and calories burned. Below is an example of the data in my table:
this is returned by:
SELECT month, day, calories FROM workouts ORDER BY year ASC, month ASC, day ASC LIMIT 12;
(month | day | calories)
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|112
3|23|169
3|23|2160
the code i've written for the above is:
public Cursor getLastTwelveDays(){
Cursor c;
String[] s = {KEY_MONTH, KEY_DAY, KEY_CALORIES};
String order = KEY_YEAR + " ASC, " + KEY_MONTH + " ASC, " + KEY_DAY + " ASC LIMIT 12" ;
c = db.query(WORKOUT_TABLE, s, null, null, null, null, order);
return c;
}
I would like to combine the rows with the same day and month into a single row like so:
3|2|714
3|3|945
3|4|630
3|10|446
3|16|396
3|20|255
3|22|108
3|23|2441 (112 + 169 + 2160)
Also, it would be nice if it were easy to use with android's query function.
Thanks in advance.
What you are looking for is the group by clause. Use the SUM() method to get the total calories for each date. I believe the group by clause should go before the ORDER BY clause.
SELECT month, day, SUM(calories) FROM workouts GROUP BY month, day
Sounds like you want a subquery (i.e. one query to calculate the SUM of the daily calories, inside another query that gets the calorie totals per day).
Try looking up QUERY and sub-query examples. Perhaps the query function allows you to pass a raw query into it, in order to do the kind of more advanced query that you're describing.
Without seeing your schema - look at SUM and GROUP BY as well.