Convert JTextField to integer and save to bd

-3

I have a JTextField that is populated from the database as text, I would like to save in another DB 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);
}
    
asked by anonymous 23.12.2014 / 13:15

2 answers

2

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

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

Note that a NumberFormatException will be thrown if you can not convert the String returned to an integer. So if you're not sure that this number will always be an integer, it might be worthwhile to treat with try/catch .

    
23.12.2014 / 13:53
0

Considering a treatment for the jTextField value:

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.

    
23.12.2014 / 13:39