2012-11-15 35 views
0

假設我們有一個名爲的JFrame FrmRegistration。其功能是將數據插入到名爲記錄的表中。在Java中使用STR_TO_DATE插入日期,使用PreparedStatement

MySQL的命令遞減記錄會導致如下:

+-----------+--------------+------+-----+---------+-------+ 
| Field  | Type   | Null | Key | Default | Extra | 
+-----------+--------------+------+-----+---------+-------+ 
| id  | varchar(7) | NO | PRI |   |  | 
| name  | varchar(100) | NO |  | NULL |  | 
| birthday | date   | NO |  | NULL |  | 
+-----------+--------------+------+-----+---------+-------+ 

FrmRegistration有一個的JFormattedTextField生日輸入,我們會打電話給ftfBirthday。在Netbeans中,我們通過右鍵單擊它並轉到屬性 - >代碼選項卡 - >變量名稱,將名稱放入組件中。或者右鍵單擊 - >自定義代碼 - >重命名...按鈕。

右鍵單擊字段並轉到屬性,然後在FormatterFactory中單擊「...」按鈕。使用以下代碼創建自定義字段:####/##/##

JFormattedTextField的原因是,用戶不會通過鍵入斜槓來損失時間。它們自動出現。

應該在FrmRegistration中調用Insert的按鈕源代碼?

回答

3

在轉到源代碼之前,右鍵單擊日期字段並轉到屬性。複製文本的內容。它應該是(A =一個空格):

AAAA/AA/AA

它將在使用 「}否則如果(」//「.equals(生日)){」 行。

(見適當的參數代碼)

我增加了一些額外的東西,就像如果字段爲空檢查。

try { 
       Class.forName("com.mysql.jdbc.Driver"); 

       try (Connection con = DriverManager.getConnection(

           "jdbc:mysql://localhost/database_name_here", 
           "username_here", "password_here")) { 

        String if = txtId.getText(); 
        String name = txtName.getText(); 
        String birthday = ftfBirthday.getText(); 

        PreparedStatement stmt = con.prepareStatement(

          "INSERT INTO records " 
          + "(id, name, birthday)" 
          + "VALUES(?,?,STR_TO_DATE(?,'%Y/%m/%d'))"); 

        if (id.isEmpty()) { 
         JOptionPane.showMessageDialog(null, 
           "The ID field must be completed!"); 

        } else if (name.isEmpty()) { 
         JOptionPane.showMessageDialog(null, 
           "The Name field must be completed!"); 

        } else if (" // ".equals(birthday)) { 
         JOptionPane.showMessageDialog(null, 
           "The Birthday field must be completed!"); 

        } else { 

         stmt.setString(1, id); 
         stmt.setString(2, name); 
         stmt.setString(3, birthday); 

         stmt.executeUpdate(); 

         JOptionPane.showMessageDialog(this, " Data was saved successfully! "); 

        } 

       } 

      } catch (SQLException e) { 
       JOptionPane.showMessageDialog(this, "SQL command error " 
         + e.getMessage()); 

      } catch (ClassNotFoundException e) { 
       JOptionPane.showMessageDialog(this, 
         " Database driver not found "); 

     } 

就是這樣。希望它能幫助別人! :-)