How to insert into JDate chooser value into db - java

I have a JDateChooser in my form. and I need to insert it's Date value into DB.
I used this method just after "public class Nonacademic extends javax.swing.JInternalFrame {" ,
and the method I used is mentioned below,
public static java.sql.Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null) {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
JOptionPane.showMessageDialog(null, "No Dates are Specified!");
return null;
}
and In my Add button's actionPerformed event I used
Connection c=DBconnect.connect();
Statement s = (Statement) c.createStatement();
PreparedStatement statement = c.prepareStatement("INSERT into nonacademic ( empId, name, Dob, JoinedDate) VALUES (?,?,?,?)");
statement.setString(1,txtEmpId.getText());
statement.setString(2, txtNmae.getText());
statement.setDate(3,convertUtilDateToSqlDate( (Date) jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate( (Date) jDateChooserDateOfJoined.getDate()));
statement.executeUpdate();
Problem is It is gives this error,
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
When I search for a solution to this, I found that this runtime error happens due to Parent class Instance is casting into child class.So can u give me a suggestion to correct this code.
Note:
After done coding above code when I select a Date in JDateChooser It appears as this 2015-08-06, Before code above stuff It appears as Aug 6,2015.

Try below statements,
statement.setDate(3,convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate(jDateChooserDateOfJoined.getDate()));
Reason:
This is because of import statements. You might have imported only java.sql.Date or java.sql.* statement in your code. All "Date" class you mentioned in your program will be treated as java.sql.Date. So JVM is trying to converting java.util.Date to java.sql.Date in those statement and throwing exception.

Related

I am trying to fetch data from database where date = jdatechooser:

I have a table with a column datetime i want to retrieve data from database where date is specified in jdatechooser but em continously getting error:
Cannot make a static reference to the non-static method getDate() from
the type JDateChooser
Here is the code:
public void actionPerformed(ActionEvent e) {
Date date = JDateChooser.getDate();
try{
String query = " Select *from Transactions WHERE "+date+"=? ";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e1){
e1.printStackTrace();
}
}
It's theoretically possible to have a window with lots of different JDateChooser controls on it. So when you refer to one of them, you need to specify which one, rather than just calling it JDateChooser.
Somewhere in your class, you'll have a declaration something like
private JDateChooser theChooser;
where you declare a variable to refer to your JDateChooser - that is, you give it a name. Now, you need to use the EXACT SAME NAME when you refer to your JDateChooser in your actionPerformed method. For example
Date date = theChooser.getDate();
But don't write theChooser - write whatever name YOU gave the JDateChooser when you declared the variable.

How can i insert value in timestamp datatype column in SQL using java or JSP

I have tried to add value using preparedStatement.
----Some piece of Code----
`
String query = "INSERT INTO COMMENTS VALUES(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.setTimestamp(3, now);
3rd column is timestamp type. But this is showing error.
It shows a whole list of packages needed to be imported. But when i import a package, it asks me to create a variable named 'now'.
Help me, how to fill timestamp field in database using java or JSP.
Thanks in advance
'now' needs to be of type java.sql.Timestamp
you can run a quick test by doing
ps.setTimestamp(3,getCurrentTimeStamp());
where getCurrentTimeStamp() is
public java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
To shorten HocusPocus correct answer even more, maybe
ps.setTimestamp(3, new java.sql.Timestamp(java.lang.System.currentTimeMillis()));

java sql - insert timestamp into sql database

I'm trying to insert a timestamp into a database, but my code throws an exception, which tells me it's something with my sql statement.
The exception message shown is:
"Fout in Rit_ToevoegenController.okKnop(): SQLException in RitDB.voegRitToe() - statement"
okKnop is a different method that calls voegRitToe().
The type of the column called 'starttijd' is TIMESTAMP, and the DB Data type is DateTime.
i'm fairly certain that it's the timestamp that causes problems, because the other 2 are just a String and an int.
Any help with making it work would be greatly appreciated. I need to insert both the time and date into the database for comparing later.
public void voegRitToe(Rit r) throws DBException{
Timestamp starttijd = new Timestamp(System.currentTimeMillis());
//Date date = new Date(starttijd.getTime());
try(Connection conn = ConnectionManager.getConnection();){
try(PreparedStatement stmt = conn.prepareStatement("insert into rit(starttijd, lid_rijksregisternummer, fiets_registratienummer) values(?,?,?)");){
stmt.setTimestamp(1, starttijd);
stmt.setString(2, r.getLid().getRegisterNr());
stmt.setInt(3, r.getFiets().getRegisNr());
stmt.execute();
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - statement");
}
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - verbinding");
}
}
TIMESTAMP and DATETIME serve different purposes; TIMESTAMP is for automatic time stamping.
java.util.Date starttijd = new java.util.Date(System.currentTimeMillis());
java.util.Date starttijd = new java.util.Date(); // Or this
I guess you came at Timestamp, as java.sql.Date wraps java.util.Date by setting the time part to zero!
If the database server's time is correct, one could also do:
... VALUES(NOW(), ?, ?)
By the way, java 8 introduces new date/time classes and "improve" upon the JDBC usage, if you have a java 8 compliant driver.

Searching between 2 date

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();
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());
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);

Java: creating a date object from a string and inserting into MySQL

Anytime I have to handle dates/times in java it makes me sad
I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"
Eh WTF?
Here is the offending code.
for(int i = 0; i < flights.size(); i++){
String[] details = flight[i].toString().split(":");
DateFormat formatter ;
formatter = new SimpleDateFormat("ddMMyyyy");
Date date = formatter.parse(details[1]);
PreparedStatement pstmt = conn.prepareStatement(insertsql);
pstmt.setString(1, details[0]);
pstmt.setDate(2, date);
pstmt.setString(3, details[2] + "00");
pstmt.setString(4, details[3]);
pstmt.setString(5, details[4]);
pstmt.setString(6, details[5]);
pstmt.setString(7, details[6]);
pstmt.setString(8, details[7]);
pstmt.setString(9, details[8]);
pstmt.executeUpdate();
}
PreparedStatement.setDate takes a java.sql.Date, not a java.util.Date.
(Out of interest, how come you're not actually seeing this as a compile-time error? Your life will become a lot easier if you can resolve compilation failures without having to get to that point in a test run...)
My guess is that you mixed java.util.Date and java.sql.Date ...
String to MySQL Date/Time
import java.sql.Date;
import java.sql.Time;
statement.setDate(4, Date.valueOf("2009-08-26"));
statement.setTime(5, Time.valueOf("12:04:08"));

Categories

Resources