You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

  1. You're parsing the literal string "DOB" instead of the actual date value from your ResultSet — that's a critical mistake! The line sdf.parse("DOB") tries to turn the word "DOB" into a date, which obviously won't work.
  2. Typos: You wrote calender instead of calendar when setting the component's calendar.
  3. Format Mismatch: You stored the date using yyyy-MM-dd format, but tried to parse it with dd-M-yyyy — this will throw a ParseException even 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:45:19