如何从MySQL数据库取回日期并转换为Calendar(Java Swing场景)
Fix: Retrieve Date from MySQL and Convert to Calendar for Swing GUI Update
Hey, let's break down why your date parsing is failing and fix it step by step:
The Main Issues in Your Code
- You're parsing the literal string
"DOB"instead of the actual date value from your ResultSet — that's a critical mistake! The linesdf.parse("DOB")tries to turn the word "DOB" into a date, which obviously won't work. - Typos: You wrote
calenderinstead ofcalendarwhen setting the component's calendar. - Format Mismatch: You stored the date using
yyyy-MM-ddformat, but tried to parse it withdd-M-yyyy— this will throw aParseExceptioneven if you use the right value.
Corrected Code with Explanations
Here's the fixed version of your code, with improvements for safety and reliability:
String idpop = JOptionPane.showInputDialog(null , "Enter Student ID to update record:"); int sid = Integer.parseInt(idpop); // Use try-with-resources to auto-close database resources (avoids memory leaks!) try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/schl","root","root"); PreparedStatement ps = con.prepareStatement("select * from stud_info where ID=? ")) { // Parameterized query to avoid SQL injection (way safer than string concatenation!) ps.setInt(1, sid); ResultSet rs = ps.executeQuery(); if (rs.next()) { // Load other fields as before id1.setText(rs.getString("ID")); nm1.setText(rs.getString("Name")); em1.setText(rs.getString("Email")); mb1.setText(rs.getString("MobNo")); addr1.setText(rs.getString("Address")); ssc1.setText(rs.getString("SSCMrks")); hsc1.setText(rs.getString("HSCMrks")); // Handle the date correctly String dobFromDb = rs.getString("DOB"); if (dobFromDb != null && !dobFromDb.isEmpty()) { // Use the SAME format you used to store the date (yyyy-MM-dd) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse(dobFromDb); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); db1.setCalendar(calendar); // Fixed the typo here! } catch (ParseException e) { // Show user-friendly error instead of crashing JOptionPane.showMessageDialog(null, "Failed to load date: " + e.getMessage()); e.printStackTrace(); } } } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Database error: " + e.getMessage()); e.printStackTrace(); }
Bonus: Even Better Approach If Using DATE Type in MySQL
If your DOB column is a MySQL DATE type (not a string), you can skip the SimpleDateFormat entirely and get the date directly:
java.sql.Date sqlDate = rs.getDate("DOB"); if (sqlDate != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(sqlDate); db1.setCalendar(calendar); }
This is cleaner and avoids any format-related errors.
Key Takeaways
- Always use parameterized queries to prevent SQL injection attacks.
- Use try-with-resources for database connections/statements to ensure resources are closed properly.
- Match your date parsing format exactly to the format you used to store the date.
- Never hardcode column names as literal strings when parsing dates (like you did with
"DOB").
内容的提问来源于stack exchange,提问作者MRUNAL MUNOT
相关产品推荐
相关产品推荐

