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[code]/*
- 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 {//
private Connection conexao = null;
////
public Conexao()
{}
////
/**-
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();
}
}
//
}[/code]
-
CargoBean.java[code]/*
- To change this template, choose Tools | Templates
- and open the template in the editor.
*/
package br.com.mjjoias.bean;
/**
*
-
@author markin
*/
public class CargoBean {
//
private int IdCargo;
private String Nome;
////
/**-
@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;
}
//
}[/code]
-
@return the IdCargo
CargoData.java (só o metodo de busca)[code]public List Lista(String Nome){
PreparedStatement pstmt = null;
ResultSet rs = null;
List lista = new ArrayList();
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;
}[/code]
Tabela no Banco:
create table cargos(
IdCargo int not null primary key identity,
Nome varchar(50) not null
)
Se eu concatenar diretamente o parâmetro de busca na String SQL funciona, desse jeito:
String SQL = "SELECT IdCargo, Nome FROM Cargos WHERE Nome LIKE '%"+Nome+"%'";
Minha duvida é porque com PreparedStatement não está funcionando.
Se alguém souber e puder me ajudar, fico grato.