Java with MySQL (JDBC) - Type YEAR

1

I am having a question on how to write a YEAR type in MYSQL database using a Java application from a TextField, I have already tried to use Date type, but I can not get just the year to write to the YEAR field in the YEAR field. I tried with SimpleDateFormat but it ends up generating a new data type that does not work with the preparedStatement method of JDBC.

Below is the diagram of the bank and the Entity class and View:

View:

privatevoidbtnSalvarActionPerformed(java.awt.event.ActionEventevt){Livroslivros=newLivros();LivrosDAOlivrosDao=newLivrosDAO();livros.setTitulo(tfTitulo.getText());livros.setIsbn(Integer.parseInt(tfISBN.getText()));livros.setAno(Short.valueOf(tfAno.getText()));livros.setPaginas(Integer.parseInt(tfPaginas.getText()));livros.setGenerosEntity((Generos)cbGenero.getSelectedItem());livros.setAutoresEntity((Autores)cbAutor.getSelectedItem());livros.setEditorasEntity((Editoras)cbEditora.getSelectedItem());if(tfCodLivro.getText().isEmpty()){livrosDao.inserir(livros);livrosTableModel.addLivro(pesquisar(livros));}else{livros.setCodLivro(Integer.parseInt(tfCodLivro.getText()));livrosDao.atualizar(livros);livrosTableModel.updateLivros(linhaSelecionada,livros);}this.setVisible(false);}

DAO:

publicbooleaninserir(Livroslivro){try{super.abrirConnection();super.preparedStatement=super.connection.prepareStatement(INSERT);preparedStatement.setInt(1,livro.getIsbn());preparedStatement.setString(2,livro.getTitulo());preparedStatement.setInt(3,livro.getAutoresEntity().getCodAutor());preparedStatement.setInt(4,livro.getEditorasEntity().getCodEditora());preparedStatement.setInt(5,livro.getGenerosEntity().getCodGenero());preparedStatement.setShort(6,livro.getAno());preparedStatement.setInt(7,livro.getPaginas());returnpreparedStatement.executeUpdate()!=0;}catch(SQLExceptionex){JOptionPane.showMessageDialog(null,"Erro ao inserir o registro" + ex.getMessage());
        return false;
    } finally {
        fecharPreparedStatement();
        fecharConnection();
    }

}

Entity:

public short getAno() {
    return ano;
}

public void setAno(Short ano) {
    this.ano = ano;
}
    
asked by anonymous 01.07.2017 / 23:38

1 answer

0

Your getter method getAno() returns a primitive type "short," which is different from the Short type of java.sql.Short . You should use java.sql.Short, which is the type used by the driver.

  

YEAR [(2 | 4)] YEAR If yearIsDateType configuration property is set to   false, then the returned object type is java.sql.Short . If set to true   (the default), then the returned object is of type java.sql.Date with   the date set to January 1st, at midnight.

Ref link

    
21.12.2017 / 18:36