Convert Jtextfield to integer and save to bd

Asked

Viewed 6,070 times

-3

I have a JTextField which is populated from the database as text, would like to save in another BD as int. Could someone please help me?

My code:

String sql = "INSERT INTO  ass_cidade(id_cidade) VALUES(?)";
try {
    pst = ConnectDB().prepareStatement(sql);

    //CidadeAtendida cidade = (CidadeAtendida) txtCidadesAtendidas.getText();

    pst.setString(1, txtCidadesAtendidas.getText());

    pst.execute();
    JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "Cadastro efetuado com sucesso", JOptionPane.INFORMATION_MESSAGE);

} catch (SQLException erro) {
    JOptionPane.showMessageDialog(null, erro);
}

2 answers

2

The method getText returns a String with the value in JTextField, then basically what you need to do is parse that value for an integer.

int valor = Integer.parseInt(textField.getText());

It is worth mentioning that a NumberFormatException if it is not possible to convert the String returned to an integer number. So if you’re not sure that this number will always be an integer, maybe it’s interesting to do the treatment with a try/catch.

  • This example did not work.

  • Thank you all For your help, it worked out here.

  • 3

    Mark one of the answers as correct, if any helped you Daivid. Or, if you found the answer yourself, post a reply with the solution.

0

Considering a treatment for the value of jTextField:

String valorTextField;
Integer valorIntegerTextField;
try{
    valorTextField = campoTextField.getText();
    //Capturo o valor do campoTextField e coloco em valorTextField.
    valorIntegerTextField = Integer.parseInt(valorTextField)
    //Transformo o valor de valorTextField em Integer e insiro em valorIntegerTextField.
    //Aqui pode ocorrer a exceção NumberFormatException, onde o campo de TextField conter algum valor que não seja inteiro.
}catch(NumberFormatException e){
    e.printStackTrace();
}

From here it would be normal inclusion in the bank.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.