Calling stored procedures from Java

后端 未结 2 1695
迷失自我
迷失自我 2021-01-22 18:55

I\'m trying to call a mySQL stored procedure from my Java application. When I call the stored procedure from mySQL workbench, it works and I get the correct number of rows depen

相关标签:
2条回答
  • 2021-01-22 19:03

    Procedure and Java code need little adoption. So lets start with the procedure:

    create DEFINER=`root`@`localhost` PROCEDURE `comprobarUsuario`(
    IN usu varchar(20),
    IN pass varchar(20),
    OUT idusuarios int)
    BEGIN
      SELECT usuarios.idusuarios
      into idusuarios
      FROM usuarios
      WHERE usuarios.nombreUsuario = usu and usuarios.contraseña = pass;
    end
    

    You want to retrieve the value "idusuarios" from the database. So you need to save it in the parameter value. Make sure parameter and value in the select clause are different from each other or provide the column name via [tablename].[column] or alias.

    Java problem: You don't need the ResultSet Object at all. To access the value from a procedure output parameter use cs.getInt() provided by the CallableStatement class.

    public void mostrarDatos(){
        Connection con = null;
        try {
            con = getConnection();
            CallableStatement cs = con.prepareCall("{CALL comprobarUsuario(?,?,?)}");
            cs.setString(1, "Jorge");
            cs.setString(2, "1627Jorge");
            cs.registerOutParameter(3, java.sql.Types.INTEGER);
            cs.executeUpdate();
    
            int resultado = cs.getInt(3);
            System.out.println(resultado);  
    
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if(con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.out.println(e);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-22 19:09
    public void mostrarDatos() 
    {
        try {
            Connection con = null;
            con = getConnection();
    
            CallableStatement cs;
            cs = con.prepareCall("{CALL comprobarUsuario(?,?,?)}");
            cs.setString(1,"Jorge" );
            cs.setString(2, "1627Jorge");
            cs.registerOutParameter(3, Type.INT);
            cs.execute();
            ResultSet rs2 = cs.getResultSet();
    
            if(rs2.next()){
                System.out.println(true);
            }
            int resultado = cs.getInt(3); // check whether the column name is correct
            System.out.println(resultado);
            con.close();
    
        } catch (Exception e) {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题