I have a DATA/TIME field in my MySQL database and I'm trying to convert it to date and time in Java. The date works fine, but in time is set to null. I have tried util.Date as well but I get the same result. How can I convert a DATE/TIME to java.sql.Date without losing the time?
This is my code
try{
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT orders.id, orders.date FROM user, orders " +
"WHERE user.username='" + user.getUsername() + "' AND user.id = orders.user");
while(resultSet.next()){
Order order = new Order();
order.setId(resultSet.getInt(1));
order.setUser(user);
order.setDate(resultSet.getDate(2));
System.out.print(order.getDate());
System.out.print( " -> " + order);
orders.add(order);
}catch(SQLException ex){
System.out.println(ex);
}
try this
java.sql.Date date = new Date(resultSet.getTimestamp(2).getTime());
You are not asking this, but you could save the date as a long in mysql and just treat it as a number.
To get the date back just do a new java.util.Date(mysqllong).
Related
I am trying to read a timestamptz data with java jdbc.
When i set session timezone (connection timezone) on postgresql, i expect to read all timestamptz columns in given timezone of the session. When i read resultset with getString() method it returns expected timestamptz value, but getTimestamp() method returns the date in default timezone of jvm.
Here is sample code:
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/tztestdb", "postgres", "123456");
Statement setTZ = connection.createStatement();
setTZ.execute("SET timezone='UTC'");
//setTZ.execute("SET timezone='Europe/Istanbul'");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT datetimetzcol,datetimecol FROM TZTEST");
ResultSetMetaData jMetadata = rs.getMetaData();
int ColumnType = jMetadata.getColumnType(1);
while (rs.next()) {
System.out.println("STRING: " + rs.getString(1) + " TYPE ->" + ColumnType);
System.out.println("TIME S: " + rs.getTimestamp(1) + " TYPE ->" + ColumnType);
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
And here is the output :
STRING: 2020-01-01 07:00:00+00 TYPE ->93
TIME S: 2020-01-01 10:00:00.0 TYPE ->93
My database table contains two columns first one is a timestamptz the secondone is timestamp. When i test a similar code in mysql retunrs identical dates unlike postgresql.
Additionally, when i read timestamptz column with a timezone information, nothing changes. Here is my additonal row:
System.out.println(rs.getTimestamp(1, Calendar.getInstance(TimeZone.getTimeZone("UTC"))));
and output is same:
2020-01-01 10:00:00.0
My expected value is:
2020-01-01 07:00:00.0
Is there a solution to avoid reading timestamptz column in jvm's default timezone. I just want to read data in session's timezone which i set it with SET TIMEZONE query.
I want to sort sql results with a date that i get from jDateChooser and display all the returned results. This is what i have done so far. So far I have only managed to get 1 result even if i looped the sorted sql results.
public void MonthlyTotalExpenses_Report(){
String typeOfReport = (String) report_type.getSelectedItem();
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText();
db databaseCon = new db();
Connection dbconnect = db.dbconnect();
if(typeOfReport == "Total expenses"){
String selectQuery = "select name,type,sum(amount),date_payed from expenses order by ? DESC";
try{
Connection con = databaseCon.dbconnect();
ResultSet rs = null;
PreparedStatement pst = null;
pst = con.prepareStatement(selectQuery);
pst.setString(1,reportDate);
rs = pst.executeQuery();
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
for(String result : results) {
System.out.println(result);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I want sort the results like this (for example -> 2017-01-01 to the date user select with jDateChooser) and print all the records available within that period. I just figured the sql query i wrote is wrong. It only prints the 1st value of the name column in the database. Help me to figure out how to sort according what i have mentioned above and print all the results that returned.
You might want to set the date in the where condition in your query.
select name,type,sum(amount),date_payed from expenses where date_payed = ? order by 4 DESC
Consider obtaining Date from String.
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText(); // "2017-01-01"
DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
Date date = format.parse(reportDate);
Then set your param with
pst.setDate(1,reportDate);
I want to search column called name in my work table by searching date. Other columns are id(primary key) and mydate. I can't find what is wrong with my code. I'm using jdbc class for db connection.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jDateChooser1.getDate());
String time1 = dateSpinner1.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
try {
ResultSet rs =db.getData("SELECT * FROM work WHERE mydate = '"+date1+"'");
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
date is the name of a function in MySQL. You'll need to wrap it in ` characters:
ResultSet rs =db.getData("SELECT * FROM work WHERE `date` = '"+date1+"'");
One possible error may be that in database hours minutes and seconds are not 0:0:0 and from datechooser you are getting these fields as 0 : 0
Could you pass the date1 as date in the statement (as parameter)?
"SELECT * FROM work WHERE date = ?" and pass parameter as date
I have a database in which I am saving messages with tiemstamps. I have table created with this code:
CREATE TABLE messages (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msgid VARCHAR(64) UNIQUE,
payload TEXT,
sender VARCHAR(255),
cur_timestamp TIMESTAMP(3)
);
This all works perfectly. However, now I am trying to delete some rows with timestamp older than some specified by user. This is done in Java part of my system like this:
// get current timestamp
Date date = new Date();
// timestamp has to be in the same format as in database
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm:ss.SSS");
String formattedDate = sdf.format(date);
System.out.println("Current time: " + formattedDate);
// subtract desired time
if (msgOld.equals("hour")) {
date.setTime(date.getTime() - ONE_HOUR_MILLISCONDS);
formattedDate = sdf.format(date);
} else if (msgOld.equals("day")) {
date.setTime(date.getTime() - ONE_DAY_MILLISCONDS);
formattedDate = sdf.format(date);
}
This, too, works fine - the constants look like this: final long ONE_HOUR_MILLISCONDS = 60 * 60 * 1000;
The only problem is that I dont know how to write the query in JDBC. I tried doing this:
// prepare query
String query;
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
} else {
query = "DELETE FROM messages WHERE cur_timestamp < " + date + ";";
}
but it says I have an error in my SQL statement (the second one, the one with TRUNCATE works fine). I tried putting formattedDate instead of date in the statement, too.
Whats wrong with it (probably something really simple - maybe difference between java.util.Date and SQL timestamp...)? Thanks for any tips!
EDIT: Thanks for all responses... I have rewritten the code so it uses prepared statement like this:
// prepare query
String query;
PreparedStatement pstmt = null;
try {
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
pstmt=conn.prepareStatement(query);
} else {
query = "DELETE FROM messages WHERE cur_timestamp < ?;";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, timestamp.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
try {
pstmt.execute();
System.out.println("Successfully deleted messages.");
pstmt.close();
} catch (Exception e) {
System.out.println("Error with db query.");
e.printStackTrace();
}
but I am still getting SQL exception (even if I convert date to timestamp and like this Timestamp timestamp = new Timestamp(date.getTime()); and use it in the satement)
You cannot just concatenate java.util.Date objects into query string. That's wrong.
Better use PreparedStatement for this kind of things.
Take a look at this tutorial for example
exactly as #Funtik said preparedStatement could be used.
See this link here
it would not exactly sove your problem but you will get a clear idea.
I have the following SQL statement in my program:
"SELECT ANTAL_KALD,BESVARET_25_SEK,((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent,TIDSPUNKT,QUEUE "
+"FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT WHERE TIDSPUNKT BETWEEN '"+start.getYear()+"-"+start.getMonthOfYear()+"-"+start.getDayOfMonth()+
"' AND '"+end.getYear()+"-"+end.getMonthOfYear()+"-"+end.getDayOfMonth()+
"'";
this doesnt give me any resultset
the test System.out.println(rs.next()) is false
However when i in my DB writes the following:
select QUEUE,
ANTAL_KALD,
BESVARET_25_SEK,
((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent,
TIDSPUNKT
from KS_DRIFT.PERO_NKM_KØ_OVERSIGT Where TIDSPUNKT BETWEEN '2012-12-01' AND '2012-12-02' ORDER BY QUEUE
i get results.. So what is the problem? it is not giving me an error or anything
Assuming start and end are java.sql.Date objects(if not please convert), I advice you to use PreparedStatement with setDate() to set the date as below:
String sql = "SELECT ANTAL_KALD,BESVARET_25_SEK, "+
" ((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent, "+
" TIDSPUNKT,QUEUE "
+"FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT "+
" WHERE TIDSPUNKT BETWEEN ? AND ?";
PreparedStatement qStmt=connection.prepareStatement(sql);
qStmt.setDate(1, start);
qStmt.setDate(1, end);
ResultSet rs = qStmt.executeQuery();
EDIT: To get java.sql.Date from Joda DateTime Object, please do the below:
java.sql.Date startDate = new java.sql.Date(start.toDate().getTime());
java.sql.Date endDate = new java.sql.Date(end.toDate().getTime());
Use these converted objects in the query.