2

I have some doubts about this one, I have gone through others topics but I still can't get the code workig properly.

My intent is to insert dates into my DB using JDBC, I'm using a jTextField (or a JformattedField, trying both ways) and all I get is an error from the database. Its Because I'm sending text instead date, so, how can I send dates ?

EDIT1: I'm trying to send date of birth.

Already made some tries, that's why I have:

SimpleDateFormat formatter  = new SimpleDateFormat ("dd/MM/yyyy"); 
    java.sql.Date data = new java.sql.Date(formatter.parse().getTime());

code:

try {   
        conecta.conn.setAutoCommit(false);
        PreparedStatement pst = conecta.conn.prepareStatement("INSERT INTO cad_pessoa(cad_cpf,cad_nome, cad_idade, cad_apelido, cad_data) values (?,?,?,?,?)");

        
        pst.setString(1, jFormattedTextFieldCPF.getText()); //pega o texto insirido e armazena no banco de dados
        pst.setString(2, jTextFieldNOME.getText()); //pega o texto insirido e armazena no banco de dados
        pst.setString(3, jTextFieldIDADE.getText()); //pega o texto insirido e armazena no banco de dados
        pst.setString(4, jTextFieldApelido.getText());//pega o texto insirido e armazena no banco de dados
        SimpleDateFormat formatter  = new SimpleDateFormat ("dd/MM/yyyy");
        java.sql.Date data = new java.sql.Date(formatter.parse().getTime());
        pst.setDate(5, formatter.parse(jFormattedTextFieldDATA.getText())); //pega o texto insirido e armazena no banco de dados
        pst.executeUpdate(); //executa o SQL
        
        
        conecta.conn.commit();
        
        
        jFormattedTextFieldCPF.setText(""); //deixa o campo vazio
        jTextFieldNOME.setText(""); //deixa o campo vazio
        jTextFieldIDADE.setText(""); //deixa o campo vazio
        jFormattedTextFieldDATA.setText("");
        jTextFieldApelido.setText(""); //deixa o campo vazio
        
        jFormattedTextFieldCPF.setEnabled(false);
        jTextFieldNOME.setEnabled(false);
        jTextFieldIDADE.setEnabled(false);
        jFormattedTextFieldDATA.setEnabled(false);
        jTextFieldApelido.setEnabled(false);
        JOptionPane.showMessageDialog(null, "Salvo!");
        
        
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(rootPane, "Erro!\n" +ex);

    }
3
  • 1
    Why are you trying to set a date using setInt? You may want to consider not using java.sql.Date, and instead use java.time.LocalDate. Commented Oct 4, 2021 at 13:59
  • Already fixed the setInt for setDate, and im trying to send date of birth. Commented Oct 4, 2021 at 14:38
  • 2
    That's great, but using java.time.LocalDate (with setObject) is the better choice when using recent JDBC drivers. Commented Oct 4, 2021 at 16:10

3 Answers 3

2

Avoid legacy date-time classes

Never use java.util.Date, java.sql.Date, SimpleDateFormat and such. These legacy date-time classes are terrible, tragically flawed in design.

The legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.

java.time.LocalDate

Parse your input string as a LocalDate.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ; 
LocalDate ld = LocalDate.parse ( input , f ) ;

Pass to your database via your prepared statement.

myPreparedStatement.setObject( … , ld ) ;

To retrieve from the database:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

In Postgres, you would define your column to be of type DATE.

Use a JDBC driver compliant with version 4.2 or later of the JDBC specification.

All of this has been covered many many times on Stack Overflow. Search to learn more.

Sign up to request clarification or add additional context in comments.

Comments

1

The setInt() method that you use is intended for integer values, and it accepts an integer. To set the date, use the PreparedStatement.setDate() method.

The java.util.Date you get from the parse() method should also be converted to java.sql.Date.

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date utilDate = formatter.parse(jFormattedTextFieldDATA.getText());
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
pst.setDate(5, sqlDate);

See the documentation on the PreparedStatement class: https://docs.oracle.com/javase/9/docs/api/java/sql/PreparedStatement.html

5 Comments

I tried use setDate but still no solution. error: incompatible types: java.util.Date cannot be converted to java.sql.Date pst.setDate(5, formatter.parse(jFormattedTextFieldDATA.getText())); //pega o texto insirido e armazena no banco de dados Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
Yes, the java.util.Date should be converted to java.sql.Date first. I've updated the code in the answer.
Seems we are in the right path, but still get an error error: cannot find symbol java.util.Date utilDate = formatter.parse(jFormattedTextFieldDATA.getText()); symbol: variable formatter location: class Pessoa
The formatter variable is declared in your code, so I can't say what's wrong without looking at the current state of your code. I've added the formatter initialization to my code sample just in case.
I deleted the formatter and didn't notice, I have put back on the code and now it's working properly, thank you so much
0

pst.setInt(5, formatter.parse(jFormattedTextFieldDATA.getText()));

This is the culprit line. See you are using setInt() method in order to set a date. That is absolutely incorrect. Use setDate() method instead.

eg: pst.setDate(5, formatter.parse(jFormattedTextFieldDATA.getText()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.