I have this query :
String sql ="select col1,col2,col3 from table where tstamp between '01/01/2014 00:00' and '01/01/2014 23:59'" ;
I want to use a PreparedStatement to setDate like this :
String sql = "select col1,col2,col3 from table where tstamp between ? and ? " ;
PreparedStatement p = connection.prepareStatement(sql);
p.setDate(1,..);
and I don't know how to do it..please help
I tried the new Date(int,int,int) constructor but it doesn't set the hours and minutes.
JDBC has three temporal types, all in the java.sql package:
Date, which contains a date without time
Time, which contains a time without date
Timestamp, which contains a date and a time.
You thus need to use a Timestamp, and the setTimestamp() method of PreparedStatement.
To construct a Timestamp instance from a String, use a SimpleDateFormat to parse the String into a java.util.Date object, then construct the Timestamp by passing the milliseconds obtained from this java.util.Date object.
Use java.sql.Date
try{
sql = "select col1,col2,col3 from table where tstamp between ? and ? ;
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, /**Your Date**/);
pstmt.setString(2, /**Your Date**/);
rs = pstmt.executeQuery();
.
.
.
}catch (Exception e) {
e.printStackTrace();
}finally{
sql = null;
if(rs != null){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}
For More
The problem is that the Date object from java.sql is different that the Date from java.util
Then if You use p.setDate(1,..); with a java.util.Date You will lose the time.
One possible solution could be that You passed as argument a Date from java.sql
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 am trying to execute a select query using prepared statement in Java.
In Where clause im checking for a condition on Timestamp type column as shown below.
String selectSQL = "select * from db.keycontacts WHERE CREATEDDATETIME>?";
PreparedStatement preparedStatement = connect.prepareStatement(selectSQL);
preparedStatement.setTimestamp(1, convertStrToTimestamp(lastSyncTimeStamp));
resultSet = preparedStatement.executeQuery(selectSQL );
//function to convert timestampString to java.sql.Timestamp
private java.sql.Timestamp convertStrToTimestamp(String dateTimeStr){
java.sql.Timestamp timeStampDate = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//2015-05-11 18:26:55
java.util.Date dateObj = (java.util.Date)formatter.parse(dateTimeStr);
timeStampDate = new Timestamp(dateObj.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timeStampDate;
}
When the query is executed, getting following exception.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
So where exactly im going wrong here?
thanks in advance.
Remove the parameter from
resultSet = preparedStatement.executeQuery(selectSQL );
and change to
resultSet = preparedStatement.executeQuery( );
The query you passed in preparedStatement.executeQuery(selectSQL ); takes priority over the query you passed in connect.prepareStatement(selectSQL); which is the simple string ("select * from db.keycontacts WHERE CREATEDDATETIME>?") in which you dint set any parameter so there is a syntax error for ?
and you can also say that statement is prepared at PreparedStatement preparedStatement = connect.prepareStatement(selectSQL); since executeQuery() is inherited from Statement it will execute query without preparing it.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","rootpasswd");
PreparedStatement ps = con.prepareStatement("select p.PARKING_NUMBER, p.TYPE, p.AVAILABLE, "
+ "t.PARKING_NUMBER, t.VEHICLE_REG_NUMBER, t.PRICE, t.IN_TIME, t.OUT_TIME "
+ "from parking p inner join ticket t on p.PARKING_NUMBER = t.PARKING_NUMBER "
+ "where t.In_TIME = ?");
Timestamp ts = new Timestamp(BigDecimal.valueOf(expectedInTime.getTime()/1000d).setScale(0, RoundingMode.HALF_UP).longValue()*1000);
//To Round Half Up from millisecond (d for double) to second (long so no d) because MySQL do this.
ps.setTimestamp(1, ts);
ResultSet rs = ps.executeQuery();
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.
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 am getting a string value such as "2012-01-20" and converting it to sql.Date to insert it in the database.
code
java.util.Date DOB = new java.util.Date();
String datetext = txtDate.getText();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd");
DOB = sd.parse(datetext);
java.sql.Date sqlDate = new java.sql.Date(DOB.getTime());
String query = "ISERT INTO EMPLOYEE ('DOB')"
+ " VALUES ( ? ) ";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, sqlDate);
ps.executeQuery();
}catch(Exception ex){
System.err.print(ex);
}
When i run this code I am getting an exception ""[Microsoft][ODBC SQL Server Driver]Optional feature not implemented"
what am i doing wrong here ? pls help !
Remove single quote - ('DOB') and INSERT (misspell)
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
You may use java.sql.Date.valueOf("2012-01-20") method to convert string to sql date.
Use executeUpdate() method instead of executeQuery().
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, java.sql.Date.valueOf("2012-01-20"));
//Or use
// ps.setTimestamp(1, new Timestamp(DOB.getTime()));
ps.executeUpdate();
}catch(Exception ex){
System.err.print(ex);
}