Reputation: 9
Have a problem search between 2 date my sql statement in java
String sql ="Select * from Payment where Payment_Date between '"+date_1+"' and '"+date_2+"'";
It give me data type mismatch, I guess my problem occur in '"+date_1+"' and '"+date_2+"' ??
date_1 and date_2 I get from
Date date_1 = date1.getDate();
Date date_2 = date2.getDate();
Upvotes: 0
Views: 2770
Reputation: 49402
Start using a PreparedStatement , it will prevent SQL injections . Read this SO Q&A for more.
You can do something like this :
String sql ="Select * from Payment where Payment_Date between ? and ? ";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setDate(1, date_1 );
pstmt.setDate(2, date_2 );
// date_1 and date_2 objects should be of type java.sql.Date
Make sure you set the correct parameter types in the setXXX()
methods. Remember if the data type for Payment_Date
is DATE
and related types, you need to set java.sql.Date in the setDate() method. If the data type of column is TIMESTAMP
, then use java.sql.Timestamp and setTimestamp() method.
Footnote :-
If you have a java.util.Date
object with you , you can convert that to java.sql.Date
as :
java.sql.Date sqlDateObject = new java.sql.Date(utilDateObject.getTime());
Upvotes: 2
Reputation: 1078
Package of Date class must be java.sql not java.util.
pstmt = conn.prepareStatement("Select * from Payment where Payment_Date between ? and ?");
pstmt.setDate(1, date_1);
pstmt.setDate(2, date_2);
Upvotes: 0