I am doing code in Eclipse using Java Swing and MySQL. I am storing Date of birth using Calendar in database.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String DOB=sdf.format(db1.getDate());
I want to retrieve date from database and display in GUI for updating if user want to update.
How can I do that?
String idpop = JOptionPane.showInputDialog(null , "Enter Student ID to update record:");
int sid=Integer.parseInt(idpop);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/schl","root","root");
String sql = "select * from stud_info where ID='"+sid+"' ";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
String Sid=rs.getString("ID");
id1.setText(Sid);
String Snm=rs.getString("Name");
nm1.setText(Snm);
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
java.util.Date date = sdf.parse("DOB");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
db1.setCalendar(calender);
String Sem=rs.getString("Email");
em1.setText(Sem);
String Smb=rs.getString("MobNo");
mb1.setText(Smb);
String Saddr=rs.getString("Address");
addr1.setText(Saddr);
String Sssc=rs.getString("SSCMrks");
ssc1.setText(Sssc);
String Shsc=rs.getString("HSCMrks");
hsc1.setText(Shsc);
}
In that, I am trying for updating records, and for that, I am taking id from a user by pop-up and then It is loading data from the database but for dob, it giving error for parsing. So I want to know how to convert the date to Calendar?? I have removed the code of date after that it gave the current date and other data loading normally.
I think the problem is that
java.util.Date date = sdf.parse("DOB");is trying to parse the String"DOB", not the value ofDOBin your database.java.util.Date date = sdf.parse(rs.getString("DOB"));might work instead.You can also try passing in a dummy date string (like "2020-12-09") to see if that shows up in your GUI, without an exception, and then working to figure out how to get the string from the DB to replace the dummy date string.
Abra's comment does suggest a possible future improvement: most databases have specific date/time/timestamp types you could use instead, which might offer more guarantees than converting to a string, storing a string, and then converting back into a
Date.