Pessoal estou com problema em identificar o erro NullPointerException que segue abaixo, junto com os methodos, sou iniciante me ajudem por favor.
=============================================================
run:
java.lang.NullPointerException
Conexao com Banco de Dados estabelecida.
at conexoes.ConexaoMySql.executarSQL(ConexaoMySql.java:126)
at relatorios.DAORelatorios.gerarRelatorioFuncionario(DAORelatorios.java:85)
at controller.ControllerFuncionario.gerarRelatorioFuncionario(ControllerFuncionario.java:91)
at view.ViewFuncionario$12.run(ViewFuncionario.java:922)
CONSTRUÍDO COM SUCESSO (tempo total: 23 segundos)
===============================================================
/**
* Executa consultas SQL
*
* @param pSQL
* @return int
*/
public boolean executarSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.setResultSet(getStatement().executeQuery(pSQL));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
ex.printStackTrace();
return false;
}
return true;
}
=================================================================
public boolean gerarRelatorioFuncionario(int pCodigo) {
try {
this.abrirConexao();
this.executarSQL("select * from tbl_funcionario where codigo ='"+pCodigo+"'");
JRResultSetDataSource jrRS = new JRResultSetDataSource(getResultSet());
// caminho do arquivo dentro dos pacotes
InputStream caminhoRelatorio = this.getClass().getClassLoader().getResourceAsStream("C:/GGSoft/CGIs/src/ArquivosJasper/relatorioFuncionarios.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(caminhoRelatorio, new HashMap(), jrRS);
String nomeArquivo = "C:/GGSoft/CGIs/src/ArquivosJasper/rel.pdf";
JasperExportManager.exportReportToPdfFile(jasperPrint, nomeArquivo);
File file = new File(nomeArquivo);
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
}
file.deleteOnExit();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.getMessage(), "Erro:", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
===============================================================
public boolean gerarRelatorioFuncionario(int codigo) {
return this.dAORelatorios.gerarRelatorioFuncionario(codigo);
}
=============================================================
private void bt_imprimir_ficha_funcionarioActionPerformed(java.awt.event.ActionEvent evt) {
try {
int linhaSelecionada = tbl_funcionario.getSelectedRow();
// Verificamos se existe realmente alguma linha selecionada
if (linhaSelecionada < 0) {
JOptionPane.showMessageDialog(this, "Você deve selecionar um item na tabela antes de clicar no botão!", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
} else {
final AguardeGerandoRelatorio carregando = new AguardeGerandoRelatorio();
final ControllerFuncionario controllerFuncionario = new ControllerFuncionario();
carregando.setVisible(true);
Thread t = new Thread() {
@Override
public void run() {
// imprimir clientes
controllerFuncionario.gerarRelatorioFuncionario((int) tbl_funcionario.getValueAt(tbl_funcionario.getSelectedRow(), 0));
carregando.dispose();
}//controllerFuncionario.gerarRelatorioFuncionario((int) tbl_funcionario.getValueAt(tbl_funcionario.getSelectedRow(), 0));
};
t.start();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Erro ao executar a impressão! " + e.getMessage());
}
}
===============================================================
package conexoes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author Andre Gouveia
*/
public class ConexaoMySql {
private boolean status = false;
private String mensagem = ""; //variavel que vai informar o status da conexao
public Connection con = null; //variavel para conexao
public Statement statement;
public ResultSet resultSet;
public Connection conn;
private String servidor = "localhost";
private String driver = "com.mysql.jdbc.Driver";
private String caminho = "jdbc:mysql://localhost/gestaoescolar"; //"jdbc:postgresql://192.168.1.110:5432/escola";
private String nomeDoBanco = "gestaoescolar";
private String usuario = "root";
private String senha = "afnl@1234";
private String url = "jdbc:mysql://127.0.01/gestaoescolar?user=root&password=afnl@1234";
public ConexaoMySql() {
}
public ConexaoMySql(String pServidor, String pNomeDoBanco, String pUsuario, String pSenha) {
this.servidor = pServidor;
this.nomeDoBanco = pNomeDoBanco;
this.usuario = pUsuario;
this.senha = pSenha;
}
public static Connection getConexao() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Conectando ao banco de dados.");
return DriverManager.getConnection("jdbc:mysql://localhost/gestaoescolar", "root", "afnl@1234");
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
//abre conexão com o banco
public void abreConexao() {
try {
System.setProperty("jdbc.Drivers", driver);
setConn(DriverManager.getConnection(caminho, usuario, senha));
//JOptionPane.showMessageDialog(null, "Conectado com sucesso!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao conectar!" + ex.getMessage());
//Logger.getLogger(ConexaoSCI.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection abrirConexao(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(url);
System.out.println("Conexao com Banco de Dados estabelecida.");
}
catch (SQLException erroSQL) {
System.out.println("Erro na conexão com o Banco "+erroSQL.getMessage());
}
catch (ClassNotFoundException erroClass){
System.out.println("Erro ao carregar o Driver "+erroClass.getMessage());
}
catch (Exception e){
System.out.println("Ocoreru um erro: "+e.getMessage());
}
//VOCÊ ESQUECEU QUE RETORNAR A VARIÁVEL CONECTION AQUI (CORRIGIDO)
return con;
}
/**
* Abre uma conexao com o banco
*
* @return Connection
*/
public Connection conectar() {
try {
//Driver do PostgreSQL
Class.forName("com.mysql.jdbc.Driver").newInstance();
//local do banco, nome do banco, usuario e senha
String url = "jdbc:mysql://" + servidor + "/" + nomeDoBanco;
this.setCon((Connection) DriverManager.getConnection(url, usuario, senha));
//se ocorrer tudo bem, ou seja, se conectar a linha a segui é executada
this.status = true;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return this.getCon();
}
public void executaSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getConn().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.setResultSet(getStatement().executeQuery(pSQL));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
ex.printStackTrace();
}
}
/**
* Executa consultas SQL
*
* @param pSQL
* @return int
*/
public boolean executarSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.setResultSet(getStatement().executeQuery(pSQL));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
ex.printStackTrace();
return false;
}
return true;
}
public boolean executarUpdateDeleteSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
getStatement().executeUpdate(pSQL);
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* Executa insert SQL
*
* @param pSQL
* @return boolean
*/
public int insertSQL(String pSQL) {
int status = 0;
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.getStatement().executeUpdate(pSQL);
//consulta o ultimo id inserido
this.setResultSet(this.getStatement().executeQuery("SELECT last_insert_id();"));
//recupera o ultimo id inserido
while (this.resultSet.next()) {
status = this.resultSet.getInt(1);
}
//retorna o ultimo id inserido
return status;
} catch (SQLException ex) {
ex.printStackTrace();
return status;
}
}
/**
* encerra a conexão corrente
*
* @return boolean
*/
public boolean fecharConexao() {
try {
if ((this.getResultSet() != null) && (this.statement != null)) {
this.getResultSet().close();
this.statement.close();
}
this.getCon().close();
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Erro ao desconectar!!! " + e.getMessage());
}
return false;
}
/**
* encerra a conexão corrente
*
*/
public void Desconectar() {
if ((this.resultSet != null) && (this.statement != null)) {
try {
this.resultSet.close();
this.statement.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao desconectar!!!" + ex.getMessage());
}
}
}
/**
* @return the status
*/
public boolean isStatus() {
return this.status;
}
/**
* @return the mensagem
*/
public String getMensagem() {
return mensagem;
}
/**
* @return the statement
*/
public Statement getStatement() {
return statement;
}
/**
* @return the resultSet
*/
public ResultSet getResultSet() {
return resultSet;
}
/**
* @param mensagem the mensagem to set
*/
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
/**
* @return the con
*/
public Connection getCon() {
return con;
}
/**
* @param con the con to set
*/
public void setCon(Connection con) {
this.con = con;
}
/**
* @param statement the statement to set
*/
public void setStatement(Statement statement) {
this.statement = statement;
}
/**
* @param resultSet the resultSet to set
*/
public void setResultSet(ResultSet resultSet) {
this.resultSet = resultSet;
}
/**
* @return the servidor
*/
public String getServidor() {
return servidor;
}
/**
* @param servidor the servidor to set
*/
public void setServidor(String servidor) {
this.servidor = servidor;
}
/**
* @return the nomeDoBanco
*/
public String getNomeDoBanco() {
return nomeDoBanco;
}
/**
* @param nomeDoBanco the nomeDoBanco to set
*/
public void setNomeDoBanco(String nomeDoBanco) {
this.nomeDoBanco = nomeDoBanco;
}
/**
* @return the usuario
*/
public String getUsuario() {
return usuario;
}
/**
* @param usuario the usuario to set
*/
public void setUsuario(String usuario) {
this.usuario = usuario;
}
/**
* @return the senha
*/
public String getSenha() {
return senha;
}
/**
* @param senha the senha to set
*/
public void setSenha(String senha) {
this.senha = senha;
}
/**
* @return the conn
*/
public Connection getConn() {
return conn;
}
/**
* @param conn the conn to set
*/
public void setConn(Connection conn) {
this.conn = conn;
}
}