简体   繁体   中英

java.sql.SQLException: MONTH

please help for my assignment so im building a java program/ folder that has the auto compute of age feature and using JCalendar(JDatechooser)So far i set my dateformatstring of my jdatechooser as "yyyy-MM-dd" so my problem is inserting the chosen date in my sql i set the column of Birthdate as data type date using of course JButton sample code:

String query = "insert into walkin (FirstName, MiddleName, Surname, Birthdate, age, gender, address, contact) values (?,?,?,?,?,?,?,?) ";   
    ps = con.prepareStatement(query);      
    ps.setString(1, tfname.getText());   
    ps.setString(2, tmname.getText());   
    ps.setString(3, tsname.getText());    
    ps.setString(4, ((JTextField)date.getDateEditor().getUiComponent()).getText());   
    ps.setString(5, tage.getText());
    ps.setString(6, genderr);   
    ps.setString(7, tadd.getText());  
    ps.setString(8, tcont.getText());
    ps.execute();        
    JOptionPane.showMessageDialog(null, "Data Saved");         
    ps.close();        
    }           

Mysql is able to convert a string in format 'yyyy-mm-dd' to DATE and insert in tables. Hence your expectation seems to be correct.

Firstly hard code a date (like following) and run your code to see if mysql is processing the insert successfully and that rest of the values are correctly recorded.

ps.setString(4, '2020-01-31');  

If it works well then clearly the returned information from your widget is not in correct format, try to figure out what it returns by printing it like following an go from there.

System.out.println((JTextField)date.getDateEditor().getUiComponent()).getText());

Smart objects, not dumb strings

Pass objects of an appropriate type to your database. In the case of a date string, parse as a LocalDate object. Then pass that LocalDate object to the prepared statement using setObject using a JDBC driver supporting JDBC 4.2 or later.

So, your line:

ps.setString(4, ((JTextField)date.getDateEditor().getUiComponent()).getText());   

…should be:

String dateInput = (JTextField)date.getDateEditor().getUiComponent()).getText() ;
LocalDate ld = LocalDate.parse( dateInput ) ;
ps.setString( 4 , ld ) ;

If an improper input string were received, the LocalDate.parse command throws a DateTimeParseException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM