Storing unix timestamp in sql - java

I have a unix date in long format
Long tmpLong = (Long) local.getValue();
Here is the value of tmpLong
1485710457166
Now I want to store this variable inside of my SQLite DB, after some research I found out that you cant store Longs in SQLite so I tried this:
Long tmpLong = (Long) local.getValue();
Integer tmpInt = tmpLong.intValue();
But this gives me:
-348227250
In SQLite my datatype is INTEGER
I need help storing this unix number, any help is appreciated
Update 1
If I try store it as a long, so
localDB.add(image_id, unixTimestamp, PATH);
And then in my add method (inside SQLiteHelper class). I print the value for testing :
public void add(String image_id, Long date, String path) {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("SQL", "date " + date);
It prints 1
D/SQL: date 1

Well, that is what will happen when you truncate a 64 bit Long into a 32 bits integer...
Dont do that but try to store it like it is (as a long) because SQLite ints can handle that values, take a look into the Datatypes In SQLite
Edit:
Your code below:
public void add(String image_id, Long date, String path) {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("SQL", "date " + date);
}
if that code is so as it is posted then you are passing as parameter 1 for the date value... the method this.getWritableDatabase(); is not going to modify/change the value of the date parameter...

Related

Select sqlite android

I have a query with a condition but it is returning an empty result even though I have the data that matches these conditions. I am a beginner, so I'm not sure if this query is correct.
public Cursor raw() {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM table_person WHERE data >= " + SelecionarPeriodo.dataInicial + " AND " + "data <=" + SelecionarPeriodo.dataFinal;
Cursor res = db.rawQuery( select, new String[]{});
Log.i("String", select);
return res;
}
If I remove this condition and use a query as follows
SELECT * FROM table_person
I have the results and the columns corresponding to the dates I'm trying to get.
The way you have written your query you are actually comparing the column data with 0, because a value like 14/12/2020 is considered as an expression containing divisions between the numbers 14, 12 and 2020 which has 0 as result.
If you want to compare dates in SQLite you must use a comparable format like YYYY-MM-DD, which is the only valid text date format for SQLite.
So if you stored the dates in the column data in any other format you'd better change it to YYYY-MM-DD.
You must also use the same format for the parameters SelecionarPeriodo.dataInicial and SelecionarPeriodo.dataFinal which will be compared to data.
Then use the recommended and safe way to pass the parameters in the 2nd argument of rawQuery():
public Cursor raw() {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM table_person WHERE data >= ? AND data <= ?" + ;
Cursor res = db.rawQuery(select, new String[]{SelecionarPeriodo.dataInicial, SelecionarPeriodo.dataFinal});
Log.i("String", select);
return res;
}

Cannot remove rows comparing dates in my SQLite db Android

I am trying and searching for a while now without success to remove specific rows in my db table.
I'd like to do this as a result in comparison between DATE record value and nextday value.
I thought this would do the work
String sql = "DELETE FROM Planned_expenses_table WHERE DATE <= date('now','+1 day')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(sql);
db.close();
But it did not.
Any suggestion? I am currently storing column DATE values with the pattern "YYYY-MM-DD" which is the same returned by date().
Logcat doesn't show any exception.
So what is wrong with this piece of code? Thank you in advance.
EDIT : i've just noticed that if i change <= in > the rows are deleted, but this is very strange since saved dates are older
I managed to achieve the hoped result.
Apparently i was saving the dates in the form YYYY-M-D instead of the one written in the question. Thats why the order check <= was misbehaving.
Why not calculate the date then pass in the actual value.
var tomorrow = DateTime.Now + TimeSpan.FromDays(1);
string sql = $"DELETE FROM Planned_expenses_table WHERE DATE <= '{tomorrow.ToString("yyyy/MM/dd")}')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(sql);
db.close();

TimeStamp Difference Between Java and SQLite

Hello I have and SLQLite database in which I have table water_logs
CREATE TABLE water_logs(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
icon INTEGER NOT NULL,
date INTEGER NOT NULL);
I store date in milliseconds.
Calendar cal = Calendar.getInstance();
cal.getTimeInMillis();
My problem is I want to get the day from the my date column using strftime function. The problem is tjat java calendar timestamp is different from SLQLite time stamp
1436859563832 --> result from cal.getTimeInMillis();
1436607407--> SELECT strftime('%s','now')
What I'm actually trying to do is to group records by day. The following SQL query works just fine if value of SELECT strftime('%s','now') is paste in the date column
SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')
Seems to me that you are using 2 different value types.
When you use
Calendar cal = Calendar.getInstance();
long time = cal.getTimeInMillis();
The output value is in Milliseconds, as described here.
While when you use
strftime('%s','now')
The output value is in Seconds, as described here.
So, that might be the cause for the mismatch between the two values.
Of course that the value in seconds might undergo some rounding which might change its value a little.
I will try to provide you the best way to store Dates in SQLite database.
1) Always use integers to store the dates.
2) Use this utility method to store the dates into the database,
public static Long saveDate(Date date) {
if (date != null) {
return date.getTime();
}
return null;
}
Like,
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, saveDate(entity.getDate()));
long id = db.insertOrThrow(TABLE_NAME, null, values);
3) Use this utility method to load date,
public static Date loadDate(Cursor cursor, int index) {
if (cursor.isNull(index)) {
return null;
}
return new Date(cursor.getLong(index));
}
like,
entity.setDate(loadDate(cursor, INDEX));
4) You can also order the data by date using simple ORDER clause,
public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";
//...
Cursor cursor = rawQuery(QUERY, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// Process results
}

how to pass data from array to database using jackcess

Hi basically im doing this to retrieve data from database to array
for(i=0;i<numfilas;i++){
HashMap<Object, Object> rowdata = new HashMap<Object, Object>(cur.getNextRow());
for(j=0;j<numcolumnas;j++){
datos[posicion]=rowdata.get(nombrecolumnas[j]).toString();
posicion++;
}
}
then I pass the data to EditTexts so the user can edit it and after that I update the array, the problem is how do I take this data and send it back to the database?
Am I getting in trouble with datatypes? because the array is String type and the database had int Type, String Type, long type .....
thanks in advance
Am I getting in trouble with datatypes? because the array is String type and the database had int Type, String Type, long type .....
You could be, if any of the fields you are trying to update are Date/Time fields in Access. Jackcess is able to implicitly cast strings to numbers (in many cases, anyway), but it is not able to do that when it comes to dates.
For the sample data in a table named [Members]
MemberID MemberName SponsorID DateJoined FeePaid
-------- ---------- --------- ---------- -------
1 Gord 2014-01-16 0
the following code works fine
try (Database db = DatabaseBuilder.open(new File("C:/Users/Public/mdbTest.mdb"))) {
Table table = db.getTable("Members");
Row row = CursorBuilder.findRow(table, Collections.singletonMap("MemberID", 1));
if (row != null) {
row.put("SponsorID", "0"); // "Long Integer" in Access
row.put("FeePaid", "130"); // "Currency" in Access
table.updateRow(row);
}
else {
System.out.println("row not found.");
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
However, this will not work
row.put("DateJoined", "2014-01-23"); // "Date/Time" in Access
because Jackcess cannot implicitly cast the string value to its internal (numeric) date value, Instead you need to do something like this
org.joda.time.DateTime dt = new org.joda.time.DateTime("2014-01-23");
row.put("DateJoined", dt.getMillis());
As an alternative, you may want to investigate UCanAccess. It is a pure-Java JDBC driver that uses Jackcess to perform reads and writes on the Access database but lets you do it using more "normal" SQL methods like this:
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/Public/mdbTest.mdb");
PreparedStatement ps = conn.prepareStatement(
"UPDATE Members SET " +
"SponsorID=?, " +
"DateJoined=?, " +
"FeePaid=? " +
"WHERE MemberID=1");
ps.setInt(1, Integer.parseInt("0"));
org.joda.time.DateTime dt = new org.joda.time.DateTime("2014-01-23");
ps.setTimestamp(2, new Timestamp(dt.getMillis()));
ps.setBigDecimal(3, new BigDecimal("130"));
ps.executeUpdate();

How to get date value from SQLite in java

I have a simple table in my database:
CREATE TABLE [InformacjeZDziekanatu] (
[_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[DataWstawienia] DATE NOT NULL,
[DataModyfikacji] DATE NOT NULL,
[Tresc] VARCHAR2 NOT NULL);
In my application only what I want to do is to get value of DataWstawienia column.
I am using such method:
try {
ResultSet result = stat.executeQuery("select * from InformacjeZDziekanatu order by _id desc limit 5");
int id;
Date dataWst;
Date dataMod;
String tresc;
for(int j = 0 ; j < 5 ; j++) {
result.next();
Object[] lista = new Object[4];
id = result.getInt("_id");
dataWst = result.getDate("DataWstawienia");
dataMod = result.getDate("DataModyfikacji");
tresc = result.getString("Tresc");
lista[0] = id;
lista[1] = dataWst;
lista[2] = dataMod;
lista[3] = tresc;
dane[j] = lista;
}
}
All dates in DataWstawienia column are today's dates but using this method above I get 1970-01-01 date all the time.
What did I do wrong?
SQLIte does not have a DATE data type. Dates need to either be stored as integers (number of seconds since Unix Epoch is common) or as ISO 8601 times (e.g. 2013-10-01T12:12:12). If you say DATE in your SQLite schema you will store values as strings. Your solution of changing the type of dateWst to String acknowledges the fact that you are storing dates as strings and not as an internal date type.

Categories

Resources