my code seems to now work as intended and i can't seem to understand why . I'm trying to update a date from the database with anotherDate+14. The problem is all the updated dates have the same value. The code works when i try debugging it , but i got code different results in the db .
Here is the code :
String query="SELECT issueTime from issue";
ResultSet rs=DatabaseHandler.getInstance().execQuery(query);
try {
while(rs.next()){
java.sql.Date dbTime=rs.getDate("issueTime");
java.sql.Date initialDBTime=dbTime;
java.util.Date utilDate = new java.util.Date(dbTime.getTime());
Calendar cal=Calendar.getInstance();
cal.setTime(utilDate);
cal.add(Calendar.DATE,14);
utilDate= cal.getTime();
dbTime=new java.sql.Date(utilDate.getTime());
System.out.println("return date " + dbTime+ " Initial db time " + initialDBTime);
String qu = "UPDATE issue SET return_date=? WHERE issueTime = ?";
PreparedStatement pstmt=DatabaseHandler.getInstance().getConnection().prepareStatement(qu);
pstmt.setDate(1,dbTime);
pstmt.setDate(2, initialDBTime);
pstmt.executeUpdate();
Database results:
UPDATE : Found the problem , i was selecting only issueTime from my table .
Changed :
String query="SELECT * from issue";
Thank you for your help .
Issuetime and return_date have DateTime format, try to use Timestamp instead of Date. Here an example if you want to add 14 days:
public class TestUpdate {
public static void main(String[] args) throws ClassNotFoundException, SQLException{
TestsJdbc jdbc= new TestsJdbc();
jdbc.connect();
Connection con =jdbc.getConnection();
List<java.sql.Timestamp> listIssueDate=getIssueDate(con );
updateReturnDate(con, listIssueDate);
jdbc.closeConnexion();
}
public static java.util.Date tmsToUtilDate(java.sql.Timestamp timestamp) {
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new java.util.Date(milliseconds);
}
public static java.sql.Timestamp getTimestamp(java.util.Date date){
return date == null ? null : new java.sql.Timestamp(date.getTime());
}
public static java.util.Date addDay(java.util.Date curDate, int nbDay){
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
cal.add(Calendar.DATE, nbDay); // add 10 days
return cal.getTime();
}
public static List<java.sql.Timestamp> getIssueDate(Connection connexion) throws SQLException{
String query="SELECT issueTime from issue";
Statement statement;
List<java.sql.Timestamp> listDate= new ArrayList<java.sql.Timestamp>();
try {
statement = (Statement) connexion.createStatement();
ResultSet rs = statement.executeQuery( query);
while (rs.next()) {
//java.sql.Time dbSqlTime = rs.getTime("issueTime");//only time
//java.sql.Date dbSqlDate = rs.getDate("issueTime");//Date ex :YYYY-MM-DD
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("issueTime");// timestamp Date ex :YYYY-MM-DD hh:mm:ss
System.out.println("date:"+dbSqlTimestamp);
System.out.println();
listDate.add(dbSqlTimestamp);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listDate;
}
public static void updateReturnDate(Connection connexion, List<java.sql.Timestamp> listIssueDate) throws SQLException
{
for(java.sql.Timestamp sqlIssueDate:listIssueDate){
//
java.util.Date tempUtilDate=tmsToUtilDate(sqlIssueDate);
java.util.Date newutilDate=addDay(tempUtilDate, 14);
java.sql.Timestamp returnDate=getTimestamp(newutilDate);
System.out.println(returnDate.getTime());
System.out.println(sqlIssueDate);
//Test
String query="UPDATE issue SET return_date=? WHERE issueTime = ?";
PreparedStatement preparedStmt = connexion.prepareStatement(query);
preparedStmt.setTimestamp(1, returnDate);
preparedStmt.setTimestamp(2, sqlIssueDate);
// execute the java preparedstatement
preparedStmt.executeUpdate();
}
//connexion.close();
}
}
a screenshot of table before:
the table after update :
Related
This question already has answers here:
Java.sql.Date to Oracle database Date and Timestamp
(2 answers)
Closed 4 years ago.
I have a long type which stores the milliseconds since epoch and I want to insert that into oracle Date using jdbc prepared statements. I tried the following -
String query = "insert into tempp values(? , ?)";
ps = conn.prepareStatement(query);
String longString1 = "1521142078000";
String longString2 = "1521566664738";
long longType1 = new Long(longString1).longValue();
long longType2 = new Long(longString2).longValue();
java.util.Date d1 = new java.util.Date(longType1);
java.util.Date d2 = new java.util.Date(longType2);
ps.setDate(1, new java.sql.Date(longType1));
ps.setDate(2, new java.sql.Date(longType2));
The problem is that in Oracle it is saved without the time part and only the date-
Date1 Date2
--------------------------------------
15-MAR-18 00:00:00 20-MAR-18 00:00:00
Is there a way we can also preserve the time in Oracle. If I use the following I can see that the time part is preserved. But then that is current timestamp and I wanted the date/time corresponding to the time represented by the long milliseconds since epoch.
String query = "insert into tempp values(sysdate , sysdate)";
I am thinking you want a date in oracle, not a timestamp?
I am more of an oracle person than a java person but here it is, like the other commentators said it is java.sql.Timestamp that will get you the time part
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#//localhost/xe","scott","tiger");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "insert into tempp values(? , ?)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String longString1 = "1521142078000";
String longString2 = "1521566664738";
long longType1 = Long.parseLong(longString1);
long longType2 = Long.parseLong(longString2);
Timestamp d1 = new Timestamp(longType1);
Timestamp d2 = new Timestamp(longType2);
ps.setTimestamp(1, d1);
ps.setTimestamp(2, d2);
ps.execute();
}
}
here is the table
create table tempp (a date, b date);
here is the result
select to_char(a,'mm/dd/yyyy hh24:mi:ss'), to_char(b,'mm/dd/yyyy hh24:mi:ss') from tempp;
03/15/2018 15:27:58 03/20/2018 13:24:24
This question already has answers here:
Searching between dates in SQL with JDBC?
(3 answers)
Closed 5 years ago.
I'm making a Java program that will determine the JComboBox values set default to get the user's input to choose within daily, weekly, monthly and yearly. Now I have an idea in monthly but my query returning an Exception error. Here is my code.
Calendar timer = Calendar.getInstance();
timer.getTime();
int month = timer.get(Calendar.MONTH);
int year = timer.get(Calendar.YEAR);
int day = timer.get(Calendar.DAY_OF_YEAR);
int week = timer.get(Calendar.WEEK_OF_YEAR);
String combovalue = comboBox.getSelectedItem().toString();
if(combovalue.equals("Monthly")) {
try {
String sql = "SELECT * FROM sales WHERE date between January and February";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
JOptionPane.showMessageDialog(null, "Monthly" );
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1 );
}
Let's just start with...
String sql = "SELECT * FROM sales WHERE date between January and February";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
The sql is invalid to start with, January and February should be quoted, but, since you're trying to use a PreparedStatement, there are no parameters, so pst.setString(1, String.valueOf(day)); will fail ... I mean, where is parameter 1 anyway?
I would recommend having a closer look at Using Prepared Statements
Instead, you should be using something like...
String sql = "SELECT * FROM sales WHERE date between ? and ?";
try (PreparedStatement pst = connection.prepareStatement(sql)) {
pst.setString(1, new java.sql.Date(fromDate.getTime()));
pst.setString(2, new java.sql.Date(toDate.getTime()));
try (ResultSet rs = pst.executeQuery()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
}
JOptionPane.showMessageDialog(null, "Monthly");
} catch (SQLException exp) {
JOptionPane.showMessageDialog(null, ep);
}
This assumes that sales.date is an actual date/time type.
There are a number of ways to get the start/end dates, one of the better ways would be to use the newer Date/Time API, instead of the defunct Calendar API, for example...
LocalDate startDate = LocalDate.of(year, Month.JANUARY, 1);
LocalDate endDate = startDate.plusMonths(1);
You would then need to use...
pst.setString(1, java.sql.Date.valueOf(startDate));
pst.setString(2, java.sql.Date.valueOf(endDate));
to make them compatible with java.sql.Date
Updated...
Just to verify I wasn't going insane, I wrote this simple test class...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.Month;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
try (Connection con = DriverManager.getConnection("jdbc:h2:mem:test")) {
con.setAutoCommit(true);
String make = "create table if not exists Test (id bigint identity, value date)";
try (Statement stmt = con.createStatement()) {
stmt.execute(make);
}
try (Statement stmt = con.createStatement()) {
System.out.println(">> Remove " + stmt.executeUpdate("delete from test") + " rows");
}
LocalDate ld = LocalDate.of(2017, Month.DECEMBER, 25);
for (int index = 0; index < 100; index++) {
insert(con, ld);
ld = ld.plusDays(5);
}
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("select count(*) from test")) {
while (rs.next()) {
int count = rs.getInt(1);
System.out.println("Found " + count + " rows");
}
}
}
// String sql = "select value from test";
// try (PreparedStatement stmt = con.prepareStatement(sql)) {
// try (ResultSet rs = stmt.executeQuery()) {
// while (rs.next()) {
// System.out.println(rs.getObject(1));
// }
// }
// }
LocalDate startDate = LocalDate.of(2018, Month.JANUARY, 1);
LocalDate endDate = startDate.plusMonths(1);
String sql = "select value from test where value between ? and ?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setDate(1, java.sql.Date.valueOf(startDate));
stmt.setDate(2, java.sql.Date.valueOf(endDate));
System.out.println(startDate);
System.out.println(endDate);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
java.sql.Date date = rs.getDate(1);
System.out.println(date);
}
}
}
}
}
public static void insert(Connection con, LocalDate ld) throws SQLException {
String sql = "insert into test (value) values (?)";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
java.sql.Date date = java.sql.Date.valueOf(ld);
stmt.setDate(1, date);
stmt.executeUpdate();
}
}
}
It uses a H2 Database Engine in memory database, populates it with 100 dates from December 25th 2017 to May 9th 2019.
It then performs a query for values between January 1st 2018 and February 1st 2018 and prints
2018-01-01
2018-02-01
2018-01-04
2018-01-09
2018-01-14
2018-01-19
2018-01-24
2018-01-29
So, you need to make sure that you have valid values in your database. If you're not getting anything in your table, first, verify that the database actually returns something and that your query is valid for the data you are trying to get
You need to write date between in numeric values Jan as '01-01-2018', Feb '02-01-2018' so SELECT * FROM sales WHERE date between '01-01-2018' and '02-01-2018'
Calendar timer = Calendar.getInstance();
timer.getTime();
int month = timer.get(Calendar.MONTH);
int year = timer.get(Calendar.YEAR);
int day = timer.get(Calendar.DAY_OF_YEAR);
int week = timer.get(Calendar.WEEK_OF_YEAR);
String combovalue = comboBox.getSelectedItem().toString();
if(combovalue.equals("Monthly")) {
try {
String sql = "SELECT * FROM sales WHERE date between 01-01-2018 and 02-01-2018";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
JOptionPane.showMessageDialog(null, "Monthly" );
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1 );
}
Define Sales.date and / or Try TRUNC(date) function. Or use Numeric value like
BETWEEN '01-JAN-2018' AND '01-FEB-2018'.
Remember to insert '' marks Around the date.
I am trying to write a query in my Java program to select records between two dates. I have built my dates as such:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy", Locale.ENGLISH);
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
When I query the DB I get the attached.
I cannot get the query to select any records (e.g. between 01/01/15 and 12/31/15). I have tried all sorts of combos of strftime, but to no avail.
I am a noob to Java and SQLite, so I am sure it is a dumb user error.
Sorry about my reply below.
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '01/01/15' AND '12/31/15'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015/01/01' AND '2015/12/31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015-01-01' AND '2015-12-31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL strftime('%m/%d/%Y', DateSort) BETWEEN '01/01/15' AND '12/31/15'
Above is what I have tried in Firefox SQLite Manager extension.
EDIT:
In the above, I had DateSort defined as DATETIME. I have changed to DATE and VARCHAR and run the above queries, nothing selected.
I have also tried:
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('01/01/15') AND date('12/31/15')
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('2015-01-01') AND date('2015-12-31')
Neither worked. Don't know what else to try.
EDIT:
I grabbed this small piece of code and modified it to test. It does not work. What am I missing?
public class SQLiteTest
{
public static void main(String[] args) throws Exception
{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:/Users/peterream/Desktop/Desktop Archive/Crashplan/sqlitetest.sqlite");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name TEXT, occupation TEXT, DateSort INTEGER);");
PreparedStatement prep = conn.prepareStatement(
"insert into people values (?, ?, ?);");
prep.setString(1, "Gandhi");
prep.setString(2, "politics");
prep.setDate(3, convertSQLDate("2016-04-08"));
prep.addBatch();
prep.setString(1, "Turing");
prep.setString(2, "computers");
prep.setDate(3, convertSQLDate("2015-04-08"));
prep.addBatch();
prep.setString(1, "Wittgenstein");
prep.setString(2, "smartypants");
prep.setDate(3, convertSQLDate("2014-04-08"));
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
ResultSet rs = stat.executeQuery("select * from people WHERE strftime('%Y-%m-%d', DateSort) BETWEEN '2015-01-01' AND '2015-12-31';");
while (rs.next()) {
System.out.println("name = " + rs.getString("name"));
System.out.println("job = " + rs.getString("occupation"));
System.out.println("DateSort = " + rs.getString("DateSort"));
}
rs.close();
conn.close();
}
/**
**
* This method converts input string date to sql date format
*
* #param String sqlDateIn (MM/dd/yy)
* #return java.sql.Date returnDate
*/
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
java.util.Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
}
I am looking to select 1 row 2015-04-08.
I have created two methods in java ,one of which returns the database server time and other returns the one hour ago time of database server.Now I have to use these two date time into a sql query.The code for retrieving database server time is:-
public String database_Time() throws SQLException
{
con = getConnection();
String sql = "select GETDATE()";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while(rs.next()) {
timestr= rs.getString(1);
}
System.out.println("database time is" +timestr);
return timestr;
}
Another method for retrieving one hour ago time is
public String previostime() throws ParseException, SQLException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
fixedDate = calendar.getTime();
stringDate = simpleDateFormat.format(fixedDate );
System.out.println("previous date is"+(stringDate));
System.out.println("current date is"+timestr);
return stringDate;
}
But when I use stringDate and timestr in sql query ,then I got an error that com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
Code for sql query is:-
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
Edit:-
Method through which I will retrieve the time,and will use it in my application is:-
public String [] getChartTime() throws SQLException, ParseException
{
List<String> tStr = new ArrayList<String>();
database_Time();
String atime[] = null;
previostime();
getConnection();
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next()) {
// Just get the value of the column, and add it to the list
tStr.add(rs.getString(1).substring(11,16));
}
}
catch( Exception e )
{
System.out.println("\nException in Bean in getDbTable(String code):"+e);
}
finally
{
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime= tStr.toArray(new String[tStr.size()]);
return atime;
}
How to resolve it.
shouldn't it be like this? :
String sql = "select * from vs1_bag where logtime between '"+stringDate+"' and '"+timestr+"' ";
I have retrieved the value of logtime from database and calculated one hour ago time from the retrieved logtime.the code for retrieving logtime is
public String database_Time() {
try {
con = getConnection();
String sql = "select max(logtime) from vacuum_analog_1mins";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
timestr = rs.getString(1);
}
} catch (Exception e) {
System.out.println("\nException in Bean in getDbTable(String code):" + e);
} finally {
closeConnection();
}
return timestr;
}
Code to calculate one hour ago time is:
public Date previostime() throws ParseException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
Date fixedDate = calendar.getTime();
System.out.println("previous date is" + (fixedDate));
System.out.println("current date is" + timestr);
return fixedDate;
}
Now I want to use these two variables fixedDate and timestr in my another method where these variables will be used as parameters of a sqlquery as:
List < String > timeStr = new ArrayList < String > ();
database_Time();
String atime[] = null;
database_Time();
previostime();
getConnection();
try {
con = getConnection();
String sql = "exec vcs_gauge #gauge_name=?,#first_rec_time=?,#last_rec_time=?";
clstmt = con.prepareCall(sql);
clstmt.setString(1, "vs1_bag");
clstmt.setString(2, "fixedDate");
clstmt.setString(3, "timestr");
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).substring(11, 16));
}
But no result.Please help me where I'm going wrong.I have declared these variables as global also.
This two row aren't correct
clstmt.setString(2, "fixedDate");
clstmt.setString(3, "timestr");
if in sql they are Date type try this:
clstmt.setDate(2, java.sql.Date(fixedDate.getTime()));
clstmt.setDate(3, java.sql.Date.valueOf(timestr));