Convert String to INT

Asked

Viewed 236 times

0

How to convert variable string fg in one whole?

if (connectionIsOpened)
    {
String s = "INSERT INTO jogador(nome) VALUES " + "('" + this.playerName + "'" + ")";
        connection.executeUpdate(s);

        String fg = "SELECT cod_jogador FROM jogador WHERE jogador.nome = " + "'" + this.playerName + "'"; //buscar cod_jogador onde nome_jogador = this.playerName
        connection.executeQuery(fg);
        int gh = Integer.parseInt(fg);
        String a ="INSERT INTO `jogos`( `cod_jogador`, `pontuacao`) VALUES " + "(" + gh + "," + this.points + ")"; //Inserir cod_jogador e pontuação onde nome_jogador = this.playernames
        connection.executeUpdate(a);
        connection.close();

    }  
  • fg definitely is not whole. You would not like to rescue the ResultSet returned by connection when running fg and then rs.getInt("cod_jogador")?

  • By the code, Voce does not need to convert anything, just redeem the value of cod_player, as it will insert in another query. Although I think that there would be the case of a subquery instead of two queries.

  • Good afternoon Articuno, that’s just what I need. How to do?

  • 2

    your c'Odigo this vulnerable for SQL Injection

1 answer

1

If your table column is of the type int, you need to take the value of Resultset, through the method getInt():

if (connectionIsOpened)
    {
        String s = "INSERT INTO jogador(nome) VALUES " + "('" + this.playerName + "'" + ")";
        connection.executeUpdate(s);

        String fg = "SELECT cod_jogador FROM jogador WHERE jogador.nome = " + "'" + this.playerName + "'"; //buscar cod_jogador onde nome_jogador = this.playerName
        ResultSet rs = connection.executeQuery(fg);

        if(rs.next()){
            int gh = rs.getInt(1);
            String a ="INSERT INTO `jogos`( `cod_jogador`, `pontuacao`) VALUES " + "(" + gh + "," + this.points + ")"; //Inserir cod_jogador e pontuação onde nome_jogador = this.playernames
            connection.executeUpdate(a);    
        }

        connection.close();

}  

Just remembering that you need to add import: import java.sql.ResultSet;.

Note: it is worth mentioning that, as it was alerted by @Thiagoloureiro your code may be vulnerable, if these variables you are concatenating in the query are coming from user input, such as text fields. In this answer has an exemplification of the use of PreparedStatement and other useful links about.

  • I believe it is close to what I intend to obtain but what is the "Resultset" same?

  • @Diogoneves is an interface that is used to retrieve data from the database, by the Statemente or Preparestatement class.

  • Yes yes, I understood but in Bluej, gives the following error "cannot find Symbol - class Resultset";

  • @Diogoneves you imported the class?

Browser other questions tagged

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