I'm looking for the best way to update a DateTime field in MySQL while walking thru my result set. I have found some other questions along these lines but none that addresses the Java data and SQL date formats within a rs.updateDate statement. I have attached the code that the editor is balking at.
public class EmailQueueProcess {
public static Boolean process()
{
Date processedDtm = new Date();
java.util.Date today=new java.util.Date();
Timestamp currentTimestamp=new Timestamp(today.getTime());
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
strSQL = "select * from portal.emailqueue where portal.emailqueue.processedDtm is null";
conn = com.retailapppartners.Utils.staticGetConnection().getConnection();
stmt = conn.prepareStatement(strSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//now loop through and update the process datetime values
rs = stmt.executeQuery();
ResultSetMetaData rsMetaData = (ResultSetMetaData) rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
while (rs.next()) {
// Grab some data then update the row
rs.updateDate ("processedDtm", currentTimestamp);
rs.updateRow();
}
} catch .....
updateDate() takes a java.sql.Date. So, I believe you have two options here,
Use rs.updateTimestamp("processedDtm", currentTimestamp);
Use java.sql.Date currentTimestamp = new java.sql.Date();
Per the MySQL Documentation in Table 5.1,
These MySQL Data Types - Can always be converted to these Java types
DATE, TIME, DATETIME, TIMESTAMP - java.lang.String, java.sql.Date, java.sql.Timestamp
So you can use either 1 or 2 above.
Related
The intent of my overall program is to fetch values from Access database and display in jtable for a particular date.
I have a table in access database where for_date field is stored as a Date/Time field and format is Short date(dd-MM-yyyy). Now my program requires me to retrieve the rows from the database for a particular date.I used SimpleDateFormat to convert it in the format as access database but it gives error. The error I get is:- net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc:::3.0.4 incompatible datatypes in combination.This exception may happen if you add integers representing units of time directly to datetime values using the arithmetic plus operator but without specifying the unit of date.In this specific case you have to use,for example, +1 DAY
My code is as follows:-
String table_sel = "ISGS_table";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = sdf.format(report_date.getDate());
try{
String sql = "Select reporting_date as REPORTING_DATE,for_date as FOR_DATE,outage_date as OUTAGE_DATE,outage_time as OUTAGE_TIME,stat_detail as STATION_DETAILS,res_date as RESTORATION_DATE,rest_time as RESTORATION_TIME,rest_reason as RESTORATION_REASON from " + table_sel+" where for_date='" + date1 + "'";
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String dbURL = "jdbc:ucanaccess://C:\\Users\\Dell_PC\\Documents\\SYSTEM_OUTAGE_REPORT.accdb";
con = DriverManager.getConnection(dbURL);
st = con.createStatement();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
You are receiving that error message because you are passing the value for for_date as a string literal. UCanAccess follows the Access SQL convention of using hash marks (#) as the delimiter for date/time literals.
So, this will fail with the error you cited
... WHERE for_date = '2017-02-03'
whereas this will work
... WHERE for_date = #2017-02-03#
Note that it would be considered better form if you were to use a PreparedStatement with
... WHERE for_date = ?
and pass the date value using PreparedStatement#setDate.
I'm having a hard time trying to filter data by date
MySQL Query
public DefaultTableModel getData1(Date start,Date end){
.......
String sql = "SELECT * FROM torch.new_table WHERE pro_date between '"+start+"' and '"+end+"'";
.....
}
Code for get date from a JCalendar
DefaultTableModel dm = new Products().getData1(sDate.getDate(), eDate.getDate());
Complete code is Here: http://postimg.org/image/4zycbtj4n/
Use the wildcard '?' when you are defining the query.
Replace each wildcard using setDate and a new java.sql.Date.
...
String sql = "SELECT * FROM torch.new_table WHERE pro_date between ? and ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(start.getTime());
ps.setDate(2, new java.sql.Date(end.getTime());
ResultSet rs = ps.executeQuery();
...
If you obtain a String from a JDateChooser, you can use
ps.setDate(1, java.sql.Date.valueOf(start));
ps.setDate(2, java.sql.Date.valueOf(end));
More possibilities here Using setDate in PreparedStatement
Part of code to filter data by date (Obtained from a jCalender) using MySQL
Thanks for help #RubioRic
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//dateT and dateE type jDatechooser
String get = sdf.format(dateT.getDate());
String get1 = sdf.format(dateE.getDate());
// Query to select get data from database
String sql = "SELECT * FROM date WHERE DATE(Date) >= ? && DATE(Date) <= ?";
try{
Connection conn = dataB.mySqlCon();
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, get);
st.setString(2, get1);
ResultSet rs = st.executeQuery();
I want to link the mysql database using Java, execute query returns the record of the specified period, and finally present the result in form of table in java.
How can I convert the input string into the mysql valid date and output the result?
I tried this, but failed.
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? and TransactionDate <= '"+t1+"' and id1=?);
ResultSet rs = query.executeQuery();
Thank you very much!!!
You have to set parameters to PreparedStatement instance as follows:
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? AND TransactionDate <= ? AND id1 = ?);
query.setDate(1,new java.sql.Date(t1.getTime()));
query.setDate(2,new java.sql.Date(t2.getTime()));
query.setLong(3,id);// Assuming Datatype of Id to Long and value in variable id, Change accordingly if not.
ResultSet rs = query.executeQuery();
Edit : Changed datatype of setDate from java.util.Date to java.sql.Date
I have a table where I have to do a SELECT ... BETWEEN start_date AND end_date, as well as insert Date values into the same table.
I read things like:
java.util.Date now = new java.util.Date();
pStmt.setDate( 1, new java.sql.Date( now.getTime() ) );
pStmt.setTimestamp( 2, new java.sql.Timestamp( now.getTime() ) );
pStmt.executeUpdate();
But that kind of code sets or gets the current date, doesn't it? I want to insert and select custom dates myself.
I also read it here at StackOverflow:
SELECT *
FROM myTable
WHERE ( YEAR(myfield) = '2009')
AND ( MONTH(myfield) = '1')
Is it also possible to make the Date fields String, then use StringTokenizer to extract only the day, month or year information and use them in a SELECT similar to this code? (In case my first - and simpler - idea is impossible.)
So until now, there's two possible solutions. I also need to know which one is faster since the database accessed is in a fail-safe / critical system (a bank) with lots of data.
The first approach is better, because you were able to use date functions to manipulate values.
private void executeQuery(java.util.Date startDate, java.util.Date endDate) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select ... between ? and ?";
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
//return results
ResultSet rs = pstmt.executeQuery();
rs.last();
System.out.println("last row = " + rs.getRow());
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
I Have to get a movie from a PostgreSQL database that matches a given title and release date.
title is a character(75) and releaseDate is a date. I Have this code:
String query = "SELECT * FROM \"Movie\" WHERE title = ? AND \"releaseDate\" = ?)";
Connection conn = connectionManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(query);
java.sql.Date date = new java.sql.Date(releaseDate.getTime());
stmt.setString(1, title);
stmt.setDate(2, date);
ResultSet result = stmt.executeQuery();
but it's not working because the releaseDate is not matching when it should.
The query SELECT * FROM "Movie" WHERE title = A_MOVIE AND "releaseDate" = A_DATE works perfectly on a command shell using psql
The problem was in the database because of time format was changed from dd/MM/YYYY to MM/dd/YYYY.
Thanks