Getting data according to last hours from sqlite - sqlite

I want to get records out of sqlite database according to hours. following are my questions
1) I have to extract all data from sqlite for past one hour. I have tried following query but it provide me data for all the hours in present day
Query:
SELECT * FROM Table1 where Date >= datetime('now','-1 hours')
Where Table1 is my table name and Date is coloumn name of type DATETIME
Eg: there are following record in database
When I fire query in sqlite firefox browser tool it returns me
which I do not want.
What should be the query to get past 1 hour data from database
2) What should be query to get the value out of database according to every hours, like I have to get data for past 1 hour, then data of past 1-2 hour, the data of past 2-3 hour i.e an hour data between two hours?
Any Help will be appreciated.

Use this query for question 1 -
`select * from Table1 where(Date between '(Select Date from Table1 order by Date asc limit 1)' and 'date1');`
date1 should be in formate yyyy-MM-dd hh:mm:ss(for example 2015-10-21 08:00:00).
In date1 you can put before 1 hour datetime.
it is working in SQLite Manager.
For question 2 -
you have to get data for every hour separately using below query
select * from Table1 where(Date between 'date1' and 'date2');

Finally I found the solution to my own question
Following is the code which worked for me
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
String startDate = dateFormat.format(date);
String endDate = "";
for (int i = 1; i <= 24; i++) {
System.out.println("Start Date:- " + startDate);
calendar.add(Calendar.HOUR_OF_DAY, -1);
date = calendar.getTime();
endDate = dateFormat.format(date);
System.out.println("End Date:- " + endDate);
String data = dbAdapter.getOutDoorHourlyData(startDate, endDate);
System.out.println("Hourly Average:- " + data);
startDate = endDate;
endDate = "";
}
public String getOutDoorHourlyData(String startDate, String endDate) {
double outdoorHourly = 0;
Cursor cursor = _sqliteDB.rawQuery("Select AVG("
+ COLOUMN_NAME + ") from (Select * FROM "
+ TABLE_NAME + " where " + COLOUMN_NAME + " >= '"
+ endDate + "' and " + COLOUMN_NAME + " < '" + startDate
+ "')", null);
try {
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
outdoorHourly = cursor.getDouble(0);
} while (cursor.moveToNext());
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
String hourlyData = decimalFormat.format(outdoorHourly);
hourlyData = hourlyData.replace(",", ".");
return hourlyData;
}
}
I hope it will help someone in future

Related

Working with Date, Time in Google Apps Script

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}

Retrieving Int Value from SQLite database

I am trying to retrieve an integer from my SQLite database and my current query crashes my program. This is what I have so far:
*/
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
db.execSQL(query);
int win = Integer.parseInt(query);
return win;
}
I am not sure why this will not work. Thanks in advance.
You are trying to convert the value SELECT ......... into a number as per int win = Integer.parseInt(query);.
For a SELECT statment you need you need to retrieve a Cursor (result set), via either the query or rawQuery SQLiteDatabase method and then extract the value(s) from the method and to then access the respective column from the respective row(s).
I believe that you would use something like :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1; //<<<<<<<<<< ADDED default value to return if no row found
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
Cursor csr = db.rawQuery(query,null); //<<<<<<<<<< CHANGED to get the Cursor returned
// ADDED the following IF construct
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
//int win = Integer.parseInt(query); //<<<<<<<<<< DELETED (commented out)
csr.close(); //<<<<<<<<<< ADDED should always close a Cursor when done with it
return rv; //<<<<<<<<<< return the value (-1 if no row found)
}
This assumes that you just want the value from a single row as identified by the WHERE clause.
If possible it is recommended to a) not build the query with direct values (makes it vulnerable to SQL Injection) and to b) utilise the convenience query method.
Apply both a and b and your code could be :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = COL2 + "=?"; //<<<<<<<<<< where clause without where and ? for value that will be passed
String[] whereargs = new String[]{String.valueOf(id)}; //<<<<<<<<<< arguments used by the whereclause ? replaced on a 1 for 1 basis
String[] columns = new String[]{COL3}; //<<<<<<<<<< the columns to extract as a String array
Cursor csr = db.query(TABLE_NAME,columns,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
csr.close();
return rv;
}

How to get data row by date wise where i pass date picker's date and store data as long format date

When i call getAllInvoice(Date date) to get observable invoice list by passing date from date picker but it's return empty list please help how to get invoice observable list passing date picker's date where i store date as long format in database that example i provided below.
public VBox getBody() {
DatePicker datePicker = new DatePicker();
datePicker.setPrefWidth(width);
datePicker.setValue(LocalDate.now());
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getValue().getYear(),datePicker.getValue().getMonthValue(),datePicker.getValue().getDayOfMonth());
ListView<String> invoiceListView = new ListView<>();
invoiceListView.setPrefWidth(width);
invoiceListView.setPrefHeight(550);
ObservableList<Invoice> invoiceObservableList = connection.getAllInvoice(Date.valueOf(datePicker.getValue()));
datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
invoiceObservableList.clear();
invoiceObservableList.addAll(connection.getAllInvoice(Date.valueOf(datePicker.getValue())));
});
ListChangeListener<Invoice> listener = new ListChangeListener<Invoice>() {
#Override
public void onChanged(Change<? extends Invoice> c) {
ObservableList<String> invoiceList = FXCollections.observableArrayList();
for (Invoice invoice : invoiceObservableList) {
Customer customer = connection.getCustomerById(invoice.getCustomerId());
invoiceList.add("#" + invoice.getId() + " - " + customer.getName() + " (" + customer.getNumber() + ")");
}
invoiceListView.setItems(invoiceList);
}
};
invoiceObservableList.addListener(listener);
ObservableList<String> invoiceList = FXCollections.observableArrayList();
for (Invoice invoice : invoiceObservableList) {
Customer customer = connection.getCustomerById(invoice.getCustomerId());
invoiceList.add("#" + invoice.getId() + " - " + customer.getName() + " (" + customer.getNumber() + ")");
}
invoiceListView.setItems(invoiceList);
VBox invoicePreview = new VBox();//addMe
invoicePreview.setPrefWidth(360);
invoicePreview.setPrefHeight(560);
invoicePreview.setAlignment(Pos.CENTER);
//invoicePreview.setStyle("-fx-background-color: green");
//invoicePreview.setPadding(new Insets(15));
invoiceListView.setOnMouseClicked(event -> {
if (event.getClickCount() == 2) {
invoicePreview.getChildren().clear();
invoicePreview.setAlignment(Pos.TOP_CENTER);
Invoice invoice = invoiceObservableList.get(invoiceListView.getSelectionModel().getSelectedIndex());
InvoicePreview preview = new InvoicePreview(invoice,sizer.getValue(100));
invoicePreview.getChildren().add(preview.printPreview());
}
});
Label massage = new Label("Please select invoice first.");
massage.setFont(new Font(invoiceWidth*5/100));
invoicePreview.getChildren().add(massage);
VBox leftVBox = new VBox(datePicker, invoiceListView);
leftVBox.setSpacing(5);
HBox mainBody = new HBox(leftVBox,invoicePreview);
mainBody.setSpacing(5);
VBox root = new VBox(mainBody);
root.setId("body");
return root;
}
and this is the Connection class's getAllInvoice(Date date) method that return observable invoice list,
public ObservableList<Invoice> getAllInvoice(Date date) {
long longDate = date.getTime();
ObservableList<Invoice> list = FXCollections.observableArrayList();
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " LIKE \'"+longDate+"\'";
System.out.println(query);
try {
connection = DriverManager.getConnection("jdbc:sqlite:" + DATA_BASE);
Statement state = connection.createStatement();
ResultSet resultSet = state.executeQuery(query);
while (resultSet.next()) {
list.add(new Invoice(resultSet.getInt(INVOICE_ID), resultSet.getInt(INVOICE_USER_ID), resultSet.getInt(INVOICE_CUSTOMER_ID), resultSet.getLong(INVOICE_DATE)));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
return list;
}
datadase file like as:
"id" "uId" "cusId" "date"
-------------------------------
"3" "1" "4" "1524636334412"
"4" "1" "4" "1524636355419"
"5" "1" "3" "1524636411858"
"6" "1" "3" "1524637462701"
"7" "1" "4" "1524638110920"
how can i get data passing Date as a argument?
Assuming that you want records for the same date (day of the month of the year) as the date passed (long) then you could use :-
SELECT *
FROM invoice
WHERE date / 86400000 = <your_date> / 86400000
<your_date> being the date passed
This is stripping of the milliseconds (i.e. divide by 1000), then stripping of the seconds (i.e divide by another 60), then stripping off the minutes (i.e. divide by another 60) and then stripping of the hours (divide by 24)
i.e. 1000 * 60 * 60 * 24 = 86400000
Based upon your example data then (where 1524636334412 is the datetime of the first row):-
SELECT *
FROM invoice
WHERE date / 86400000 = 1524636334412 / 86400000
results in :-
As such you could change :-
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " LIKE \'"+longDate+"\'";
to be
String query = "SELECT * FROM " + TABLE_INVOICE + " WHERE " + INVOICE_DATE + " / 86400000 = " + longDate + " / 86400000";

How to Select Date in SQLite

I have a problem with SQlite for DateTime in UWP-app.
Assume the SQLite DB has the following data:
PurchaseDate (Date in SQLite format)
-----------------------------------
2016-09-10 11:10:10
2016-09-10 11:10:15
2016-09-10 11:10:30
Pass in this Date:
strSQLiteDate ="2016-09-10"
I just want to check if there is any row in the tblPurchase.
There is no match from below SQL-Select. What did I miss? Did I miss the hh:mm:ss part? But I just need to check the yyyy-mm-dd part.
using (var db = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DBPath))
{
var query = db.Query<tblPurchase>("Select * From tblPurchase where PurchaseDate = " + " date('" + strSQliteDate + "')");
intcount = query.Count;
if (intcount != 0)
{
return intcount;
}
}
Edit 1
10/8/2016 10:13:26 AM
The above date will be recreated as DateTime and SQLit.Net-PCL use it to insert into SQLite DB
string[] strAr_Date = strDate.Split('/');
string strYear = strAr_Date[0].ToString();
string strMth = strAr_Date[1].ToString();
string strDay = strAr_Date[2].ToString();
string strDateTime = strDay + "/" + strMth + "/" + strYear + " " + strTime;
DateTime dt = DateTime.Parse(strDateTime);
... where PurchaseDate = date('2016-09-10')
The date() function removes the time portion from a date/time value.
But the value 2016-09-10 does not have a time portion, so it is not changed.
The PurchaseDate values still have the time portion, so you end up with a comparison like this:
... where '2016-09-10 11:10:10' = '2016-09-10'
You have to remove the time from the PurchaseDate values:
... where date(PurchaseDate) = '2016-09-10'

How to filter data from database based on YYYY-MM using Selection and SelectionArgs[] parameter in Android SQLite Query

I am storing YYYY-MM-DD and HH:MM:SS values in two separate columns in all my SQLite tables.
I have been using the following code to filter data by supplier id and date from my SQLite database.
public double addPurchaseTotal(String supplierID, String date) {
SQLiteDatabase db = helper.getReadableDatabase();
double result = 0;
String selection = VivzHelper.COLUMN_ADD_PURCHASE_SUPPLIER_ID + " =? "
+ " AND " + VivzHelper.COLUMN_ADD_PURCHASE_DATE + " =? ";
String[] selectionArgs = {supplierID, date};
Cursor c = db.query(VivzHelper.ADD_PURCHASE_TABLE,
new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_COST_PRICE + ")"},
selection,
selectionArgs,
null,
null,
null);
if (c.moveToFirst()) {
result = c.getDouble(0);
}
c.close();
return result;
}
The value for date parameter is obtained from a date picker. As mentioned earlier, date value under the VivzHelper.COLUMN_ADD_PURCHASE_DATE is stored in YYYY-MM-DD format. I would like to filter my data based on YYYY-MM (year and month alone). How can this be done?
Instead of comparing the entire string with =, check for the prefix with LIKE or GLOB:
... WHERE Supplier = 'xxx' AND Date LIKE '2015-04-%'
... WHERE Supplier = 'xxx' AND Date GLOB '2015-04-*'
(GLOB works better together with indexing.)
In Java:
String selection = ...
+ " AND " + VivzHelper.COLUMN_ADD_PURCHASE_DATE + " GLOB ?";
String[] selectionArgs = { ..., date.substring(0, 8) + "*" };
I guess you are looking for this: SQLite Date and Time Functions

Resources