I paste the code and consult from it, since I pass the field of the database from a combo and the value, the field does not take it, the value does. What happens?
public ObservableList<Categoria> buscarCategoriaPorSeleccion(
String campo, String valor
) throws SQLException {
// Declaro los elemntos
PreparedStatement st = null;
ResultSet rs = null;
ObservableList<Categoria> listaCategoria = FXCollections.observableArrayList();
Categoria categoria = null;
// Conecto con la base de datos
conectar();
try {
st = this.conexion.prepareStatement("SELECT * FROM categoria WHERE ? LIKE ?");
// Esto no funciona, si meto la variable en la query si lo hace,
st.setString(1, campo);
// Esto sin problema
st.setString(2, "%" + valor + "%");
rs = st.executeQuery();
while (rs.next()) {
categoria = new Categoria();
categoria.setIdCategoria(rs.getInt("categoria_id"));
categoria.setNombreCategoria(rs.getString("categoria_nombre"));
categoria.setDescripcionCategoria(rs.getString("categoria_descripcion"));
listaCategoria.add(categoria);
}
} catch (SQLException e) {
mensaje.error("Error SQL " + e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
mensaje.error("Error SQL " + e);
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
mensaje.error("Error SQL " + e);
}
}
}
// Desconecto de la base de datos
desconectar();
// Devuelvo la lista
return listaCategoria;
}
That is, it would only work like this: SELECT * FROM categoria WHERE "+ campo +" LIKE ?
.