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
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);
}
}
}
}
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) {
}
}