How to parse MySQL timestamp in SQLite - java

My Java application uses a MySQL database that I am trying to convert to SQLite. I was able to convert the database itself just fine, but am having an issue with the timestamps that are stored within the database.
Specifically, my timestamps were stored in the default MySQL format:
2018-04-14 16:33:00
Now, when trying to read the timestamp in SQLite, I am getting the following error:
ParseException: Unparseable date: "2018-04-14 16:33:00" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
Is there an efficient way to handle this without actually modifying the format that is stored in the database?
Here is the DDL for one of the tables where this problem exists:
create table agent_list_updates
(
update_id integer not null
primary key
autoincrement,
agent_count integer not null,
update_timestamp timestamp default CURRENT_TIMESTAMP,
user_id integer not null
constraint fk_agent_list_updates_users
references users
)
;
create index idx_agent_list_updates_idx_agent_list_updates_user_id
on agent_list_updates (user_id)
;
The query:
SELECT
agent_count,
update_timestamp
FROM agent_list_updates;
And the Java code that actually causes the error:
if (resultSet.next()) {
return resultSet.getTimestamp("update_timestamp");
} else {
return null;
}

You have to define date format, and then use it to parse your timestamp as a String from resultSet. An example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(resultSet.next()) {
Date date = formatter.parse(resultSet.getString("update_timestamp"));
System.out.println(date);
}
because there is no default constructor for Timestamp, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
but Date does not provide any such method directly.

Related

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
}

MySQL Date and time insert error

I am trying to insert date and time to a table in MySQL db from a JSP page but ended with an error:
Severe: java.sql.SQLException: Incorrect datetime value: '15/05/2015 14:00:00' for function str_to_date
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
Date format in JSP page is dd/MM/yyyy HH:MM
For ex, the date is 15/05/2015 and time is 14:00
How can I fix the problem or what is correct way of doing it?
the stored procedure:
CREATE... PROCEDURE `Add(Id int,
Date_In varchar(50),Out result int)
BEGIN
IF (select count(*) from myTable Where DATE_FORMAT(Datein, '%d/%m/%Y')=DATE_FORMAT(Date_In, '%d/%m/%Y') and id=Id) < 1 then
BEGIN
INSERT INTO myTable (id, DateIn)
VALUES (id,str_to_date(Date_In,'%d/%M/%Y %H:%i'));
set result=1;
END;
END if;
end
java code:
String date = request.getParameter("date");
String time = request.getParameter("time");
String dateTIme = date + " " + time + ":00";
and insert statement goes here.
could you change
VALUES (id,str_to_date(Date_In,'%d/%M/%Y %H:%i')
to
VALUES (id,str_to_date(Date_In,'%d/%m/%Y %H:%i:%s'));
?
You are missing seconds as per the exception
You have used str_to_date(Date_In,'%d/%M/%Y %H:%i').
According to this link, %M signifies that the month is being specified in the name format. In your case, you should change your format to %d%m%Y, or alter your input to 15/MAY/2015.

Spark with Cassandra SaveToCassandra

I'm using Cassandra with spark, and I have a JavaRDD<Srring> containing 6 columns separated by , like this:
header: canal,action,time,tiemend,client
I have created a table Mytable with 6 columns:
CREATE TABLE IF NOT EXISTS ref_event_by_user_session (
canal TEXT,
action TEXT,
time timestamp,
timeend timestamp,
Client INT,
PRIMARY KEY(canal, action, time, timeend)
);
and now I want to save my JavaRDD in my Cassandra table using javaFunctions().saveToCassandra,
but I don't know how to use it. Could you please show me how to do it?
I've found the solution.
If it can help someone :)
I just create a java class table2 with canal String,
action String,
time Date,
timeend Date,
Client String,
and then :
JavaRDD<Table2> table2 = session_7.map(new Function<Tuple2<KeyTable2, ValueTable2>, Table2>() {
#Override
public Table2 call(Tuple2<KeyTable2, ValueTable2> keyTable2ValueTable2Tuple2) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date startdate = formatter.parse(keyTable2ValueTable2Tuple2._1.time.replace("+","."));
Date endtdate = formatter.parse(keyTable2ValueTable2Tuple2._1.endtime.replace("+","."));
Table2 t = new Table2(keyTable2ValueTable2Tuple2._2.canal,keyTable2ValueTable2Tuple2._2.motif,startdate,endtdate,keyTable2ValueTable2Tuple2._1.client);
return t;
}
});
javaFunctions(table2).writerBuilder("Schema", "Table", mapToRow(Table2.class)).saveToCassandra();
Note : you must add the getters in the class even if the differents variables are public.

mongodb + java + iso date search

In my mongo db database i have column like this.
"created_on" : ISODate("2014-07-02T01:38:48.713Z");
In order to to search this column am giving the following query:
db.XYZ.find({ "created_on" : ISODate("2014-07-02T01:38:48.713Z")})
Now i want to use java for retrieving this data from database:
My query is like:
DateTime dateTime = new DateTime( "2014-07-02T01:38:48.713Z" );
BasicDBObject query1 = new BasicDBObject("created_on", dateTime);
DBCursor cursor = table.find(query);
but am not getting anything query is returning 0 rows??
Any body please help how to set iso date from java.
The mongodb driver does not work with DateTime currently. You have to use java.util.Date

sql server jdbc query on datetime column

I've looked around and could not seem to find this asked specifically, on SO, but I've found similar questions like this one and lots of questions regarding SQL itself or C#...
Here is what I am seeing:
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
//parameterSource.addValue( "insertDate", DateTime.now().minusHours( 1 ).toGregorianCalendar(), Types.TIME );
parameterSource.addValue( "insertDate", new Timestamp( DateTime.now().minusHours( 1 ).getMillis() ) );
List< String > contents =
_simpleJdbcTemplate
.query(
"SELECT TOP (200) inserteddatetime, Contents FROM dbo.tsomeTable WHERE (ServiceName = 'something') and inserteddatetime > :insertDate",
new RowMapper< String >() {
#Override
public String mapRow( final ResultSet rs, final int rowNum ) throws SQLException {
System.out.println( rs.getTimestamp( "inserteddatetime" ) );
return rs.getString( "Contents" );
}
}, parameterSource );
The query "hangs"\does nothing\never returns if:
I use the uncommented Timestamp object (as presented above)
I replace the parameterSource object with DateTime.now().minusHours( 1 ).toGregorianCalendar() or DateTime.now().minusHours( 1 ).toGregorianCalendar().getTime()
I try the commented out line, but change the type to Timestamp
So, here is my question or questions...
Is there a known bug\issue with querying on datetime columns in sql server?
Why do I have to use Time and not Timestamp?
I suspect that Spring is converting the date objects over to Timestamp when I query with the object directly (as demonstrated in #2).
TIMESTAMP is a server-generated value used to help with data consistency, its not a simple data type, so for storing datetime value, avoid TIMESTAMP datatype.
Also, SQL Server TIMESTAMP is confusing, and it's deprecated. It is replaced by the ROWVERSION keyword, which should reduce confusion.

Categories

Resources