【问题标题】:Incorrect date value: 'd. MMM y' for column 'Birthday' at row 1 - MySQL exception日期值不正确:'d.第 1 行的“生日”列的 MMM y' - MySQL 异常
【发布时间】:2021-05-07 19:17:27
【问题描述】:

当我在我的 java eclipse 程序中插入数据并尝试将其插入数据库时​​,我收到此错误:

我已经安装了 MySQL connector/J 并在 MySQL workbench 中制作了数据库。

    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
feb. 03, 2021 2:31:18 PM numerologi.views.Make$5 actionPerformed
SEVERE: null
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Incorrect date value: 'd. MMM y' for column 'Birthday' at row 1

这是什么意思,我该如何解决?请帮忙!

是“ pst.setString(3, dateChooser.getDateFormatString().toString()); ”吗?

我的代码:

 dateChooser = new JDateChooser();
  dateChooser.setBounds(140, 40, 500, 20);
  panel.add(dateChooser);
  
  UpdateButton = new JButton("Update");
  UpdateButton.setFont(new Font("Tahoma", Font.BOLD, 12));
  UpdateButton.setBounds(805, 40, 85, 20);
  panel.add(UpdateButton);
  
  DeleteButton = new JButton("Delete");
  DeleteButton.setFont(new Font("Tahoma", Font.BOLD, 12));
  DeleteButton.setBounds(805, 70, 85, 20);
  panel.add(DeleteButton);
  
  ResetButton = new JButton("Reset");
  ResetButton.setFont(new Font("Tahoma", Font.BOLD, 12));
  ResetButton.setBounds(805, 100, 85, 20);
  panel.add(ResetButton);
  
  scrollPane = new JScrollPane();
  scrollPane.setBounds(10, 154, 880, 286);
  panel.add(scrollPane);
  
  table = new JTable();
  table.setBackground(Color.WHITE);
  model = new DefaultTableModel();
  Object[] column = {"Nr","Name","Birthday","Description","Other"};
  Object[] row = new Object[0];
  model.setColumnIdentifiers(column);
  table.setModel(model);
  scrollPane.setViewportView(table);
  
 
//This method contains all codes for update of Database. //

private void upDateDB() {
  try { 
  Class.forName("com.mysql.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/num clients", "root", "");
  pst = con.prepareStatement("SELECT * FROM client");
      
  rs =pst.executeQuery();
  ResultSetMetaData StData = rs.getMetaData();
      
  q = StData.getColumnCount();
      
  DefaultTableModel RecordTable = (DefaultTableModel)table.getModel();
  RecordTable.setRowCount(0);
      
  while(rs.next()){
     Vector columnData = new Vector();
          
  for (i = 1; i <= q; i++) {
     columnData.add(rs.getString("Nr"));
     columnData.add(rs.getString("Name"));
     columnData.add(rs.getString("Birthday"));
     columnData.add(rs.getString("Description"));
     columnData.add(rs.getString("Other"));
}
     RecordTable.addRow(columnData);                
          
}} catch (Exception ex) {
     JOptionPane.showMessageDialog(null, ex);
} 

      }


//This method contains all codes for creating events. //

private void createEvents() {
 
  NewButton.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) {
  try { 
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost/num clients", "root", "");   
      pst = con.prepareStatement("INSERT INTO client (Nr, Name, Birthday, Description, Other) VALUES (?,?,?,?,?)");

      pst.setInt(1,Integer.valueOf(Tnr.getText()));
      pst.setString(2, Tname.getText()); 
      //pst.setString(2, CBunknown.getActionCommand().toString()); - how to insert Checkbox here? if i want name to be unknown?
      pst.setString(3, dateChooser.getDateFormatString().toString());
      pst.setString(4, Tdescription.getText());
      pst.setString(5, Tother.getText());
      
      pst.executeUpdate();
      JOptionPane.showMessageDialog(null, "Saved");
      upDateDB();
      
  }catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(Make.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  }catch (SQLException ex) {
      java.util.logging.Logger.getLogger(Make.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
      
  }catch (Exception ex){
      JOptionPane.showMessageDialog(null, ex); 
  }}
});
  
  UpdateButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
  try { 
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost/num clients", "root", "");   
      pst = con.prepareStatement("UPDATE client SET Nr=?,Name=?,Birthday=?,Description=?,Other=? WHERE Nr = ? ");
      pst.setString(1, Tnr.getText());
      pst.setString(2, Tname.getText()); 
      //pst.setString(2, CBunknown.getActionCommand().toString()); - how to insert Checkbox here? if i want name to be unknown?
      pst.setString(3, dateChooser.getDateFormatString().toString());
      pst.setString(4, Tdescription.getText());
      pst.setString(5, Tother.getText());
      pst.executeUpdate();
      JOptionPane.showMessageDialog(null, "Updated");
      upDateDB();
          
  }catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(Make.class.getName()).log(java.util.logging.Level. SEVERE,null, ex);
  }catch (SQLException ex) {             
      java.util.logging.Logger.getLogger(Make.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
                  
  }catch (Exception ex){
      JOptionPane.showMessageDialog(null, ex); 
  }}
});
  
  DeleteButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
  DefaultTableModel RecordTable = (DefaultTableModel)table.getModel();
  int SelectedRows = table.getSelectedRow();
          
  try{
      Class.forName("com.mysql.jdbc.Driver");
      id = Integer.parseInt(RecordTable.getValueAt(SelectedRows, 0).toString());
      deleteItem = JOptionPane.showConfirmDialog(null,"Do you want to delete client?", "warning",JOptionPane.YES_NO_OPTION);
      
  if (deleteItem ==JOptionPane.YES_OPTION ) {}
      con = DriverManager.getConnection("jdbc:mysql://localhost/num clients", "root", "");   
      pst = con.prepareStatement("DELETE FROM client WHERE Nr = ? ");
      pst.setInt(1, id);
      pst.executeUpdate();
      JOptionPane.showMessageDialog(null, "Deleted");
      upDateDB();
      
      Tnr.setText(" ");
      Tname.setText("");
      Tdescription.setText("");
      Tother.setText("");
      dateChooser.setToolTipText("");
  
  }catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(Make.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
  }catch (SQLException ex) {
      System.err.println(ex);
              
  }catch (Exception ex){
      JOptionPane.showMessageDialog(null, ex); 
  }}  
});
  
  ResetButton.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      Tnr.setText(" ");
      Tname.setText(" ");
      Tdescription.setText(" ");
      Tother.setText(" ");
      }
});
  
  table.addMouseListener(new MouseListener() {
  public void mouseClicked(MouseEvent e) {
  DefaultTableModel RecordTable = (DefaultTableModel)table.getModel();
  int SelectedRows = table.getSelectedRow();   
      
     Tnr.setText(RecordTable.getValueAt(SelectedRows, 1).toString());
     Tname.setText(RecordTable.getValueAt(SelectedRows, 2).toString());
     dateChooser.setToolTipText(RecordTable.getValueAt(SelectedRows, 3).toString());
     Tdescription.setText(RecordTable.getValueAt(SelectedRows, 4).toString());
     Tother.setText(RecordTable.getValueAt(SelectedRows, 5).toString());
      
}
      
});
  table.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent evt) {
  mouseClicked(evt); }
});
      }
                      }

【问题讨论】:

  • 这是日期的格式,很可能来自您已经怀疑的行... MySQL 抱怨的模式显然在一个月中的某一天有一个数字(这可能是一个问题,但不一定是一个)和一年的一个(这更有可能是无效的)。 dateChooser.getDateFormatString().toString() 的示例返回值是什么样的?在调用getDateFormatString() 之后是否真的有必要调用toString() 方法?也许这已经弄乱了格式。哦,说到月份的名称,语言很重要。
  • 最后,您永远不应该在数据库中保护本地化日期格式。始终为 mySQL 使用标准格式,如 2021-10-23 14:55:55 并将其存储在日期时间字段中
  • @deHaar 我试图删除 toString() 并且没有任何变化。我是一个非常喜欢代码的孩子,所以我每天都在学习,有些东西对我来说没有意义。对不起! “fødselsdag”这个名字在丹麦语中只是生日,而不是一个月。
  • @ClausBönnhoff 我不确定我是否明白你的意思。我在这方面真的很绿!对不起
  • 用您的本国语言(在这种情况下似乎是挪威语或丹麦语)编写代码是可以的。我应该在工作场所用丹麦语编写代码。发布到 Stack Overflow 时,请用英文create a Minimal, Reproducible Example。你给了我们很多的代码。你能省略 Swing 的东西并在 10 行(或更短)的示例程序中重现相同的问题吗?

标签: java mysql database date


【解决方案1】:

java.time 和 JDBC 4.2

下面的代码没有经过测试,但我认为它可以工作。我基本上建议您使用现代 Java 日期和时间 API java.time 进行日期工作。 JDBC 4.2 是 Java SE 8 的一部分,完全支持 java.time 类型。

从您的JDateChooser 获取日期。不幸的是JDateChooser 是旧的并且没有升级到java.time,所以只支持设计不良和过时的类DateCalendar

Date oldfashionedDateObject = dateChooser.getDate();

转换为现代LocalDateLocalDate 是没有时间和时区的日期。

LocalDate chosenDate = oldfashionedDateObject.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDate();

将日期传递给您准备好的声明:

pst.setObject(3, chosenDate);

无论是在 Java 中还是在您的数据库进程中,也不会将您的日期保存为字符串。在 SQL 中使用 date,在 Java 中使用 LocalDate。这使您不必担心日期的格式。既不需要任何解析,也不需要任何格式。

你的代码出了什么问题?

你打电话给JDateChooser.getDateFormatString()。该方法为您提供JDateChooser 在向用户显示时用于格式化日期的格式字符串,在您的情况下为d. MMM y。不是所选日期本身。因此,无论用户选择哪个日期,您都会得到相同的字符串。接下来,您尝试将字符串d. MMM y 作为日期保存到数据库中。由于无论如何这不是一个有效的日期,保存失败,但您看到的例外情况。

链接

【讨论】:

  • 我尝试了您的建议,但没有收到任何错误,但是在单击添加按钮后运行程序时出现此消息对话框:java.lang.NumberFormatException:对于输入字符串:“”。此外,键入的信息 i Jtextfield 和 dateChooser 未在 mySQL 数据库中列出。我在这里感觉自己像个全新的傻瓜,对不起!
  • 您描述的行为的一个可能原因是您在按下按钮之前忘记在Tnr 字段中输入一个数字。我应该说这是一个新问题,所以请照原样发布。
猜你喜欢
  • 2021-05-25
  • 2017-01-16
  • 2015-04-26
  • 1970-01-01
  • 2011-10-02
  • 2014-04-27
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
相关资源
最近更新 更多