Boa Tarde pessoal tô com um problema em fazer uma busca usando PreparedStatement, não da nenhum erro, simplesmente não encontra registro algum, quando uso PreparedStatement.
Minhas classes são:
Conexao.java/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.mjjoias.data;
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* @author markin
*/
public class Conexao {
// <editor-fold desc="Atributos">
private Connection conexao = null;
// </editor-fold>
// <editor-fold desc="Construtor">
public Conexao()
{
}
// </editor-fold>
// <editor-fold desc="Métodos Públicos">
/**
* Método responsável por abrir a conexão com o BD
* @return Conexão com o BD
*/
public Connection openConnection(){
try{
// define o driver JDBC do banco de dados:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:mjjoias";
conexao = DriverManager.getConnection(url);
}catch(Exception ex){
ex.getMessage();
}
return conexao;
}
/**
* Método responsável por fechar a conexão com o BD
*/
public void closeConnection(){
try{
conexao.close();
}catch(Exception ex){
ex.getMessage();
}
}
// </editor-fold>
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.mjjoias.bean;
/**
*
* @author markin
*/
public class CargoBean {
//<editor-fold desc="Atributos">
private int IdCargo;
private String Nome;
//</editor-fold>
//<editor-fold desc="Métodos Get/Set">
/**
* @return the IdCargo
*/
public int getIdCargo() {
return IdCargo;
}
/**
* @param IdCargo the IdCargo to set
*/
public void setIdCargo(int IdCargo) {
this.IdCargo = IdCargo;
}
/**
* @return the Nome
*/
public String getNome() {
return Nome;
}
/**
* @param Nome the Nome to set
*/
public void setNome(String Nome) {
this.Nome = Nome;
}
//</editor-fold>
}
public List<CargoBean> Lista(String Nome){
PreparedStatement pstmt = null;
ResultSet rs = null;
List<CargoBean> lista = new ArrayList<CargoBean>();
String SQL = "SELECT IdCargo, Nome FROM Cargos WHERE Nome LIKE ?";
try{
StringBuffer buffer = new StringBuffer("%");
buffer.append(Nome);
buffer.append("%");
pstmt = openConnection().prepareStatement(SQL);
pstmt.setString(1, buffer.toString());
/* variável do tipo resultSet recebendo os valores retornados pela busca
* sempre que for executar um comando select o preparedStatement
* tem que executar uma Query
*/
rs = pstmt.executeQuery();
while(rs.next()){
CargoBean bean = new CargoBean();
bean.setIdCargo(rs.getInt("IdCargo"));
bean.setNome(rs.getString("Nome"));
lista.add(bean);
}
return lista;
}catch(Exception ex){
ex.getMessage();
}finally{
pstmt = null;
closeConnection();
}
return null;
}
create table cargos(
IdCargo int not null primary key identity,
Nome varchar(50) not null
)
String SQL = "SELECT IdCargo, Nome FROM Cargos WHERE Nome LIKE '%"+Nome+"%'";
Se alguém souber e puder me ajudar, fico grato.