JDBC - primeiros passos
Pessoal,
Boa tarde!
Sou muito principiante e embrionária em java e em JDBC.
Por favor poderiam me ajudar:
Preciso fazer os inserts no banco com a aplicação em JAVA e quando vou executo a classe teste está dando o erro abaixo. Usei a arquitetura em camadas.
Erro ao obter conexão com o banco de dadosException in thread "main" java.lang.NullPointerException
at br.com.certidoes.jdbc.RepositorioCertidoesBD.listar(RepositorioCertidoesBD.java:183)
at br.com.certidoes.jdbc.CadastroCertidoes.listar(CadastroCertidoes.java:32)
at br.com.certidoes.jdbc.ConexionJDBC.listar(ConexionJDBC.java:54)
at br.com.certidoes.jdbc.TesteCertidoes.main(TesteCertidoes.java:21)
A classe teste e as demais seguem. O erro é no método listar, no qual anteriormente estava dando no método inserir. Alguém poderia me ajudar?? Agradeceria muito gente.
[code]package br.com.certidoes.jdbc;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import br.com.certidoes.classes.Certidao;
public class TesteCertidoes {
// @SuppressWarnings("deprecation")
public static void main(String[] args) {
Certidao certidao = new Certidao();
certidao.setId(12);
certidao.setNome("Alvara");
certidao.setDiasEmissao("4");
certidao.setOrgao_Emissor_cnpj("4657");
ConexionJDBC.obterInstancia().cadastrar(certidao);
// ConexionJDBC.obterInstancia().inserir(certidao);
ResultSet rs = ConexionJDBC.obterInstancia().listar();
ResultSetMetaData mdata;
try {
mdata = rs.getMetaData();
int colCount = mdata.getColumnCount();
String[] colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = mdata.getColumnName(i);
}
rs.beforeFirst();
while (rs.next()) {
String[] rowData = new String[colCount];
for (int i = 1; i <= colCount; i++) {
rowData[i - 1] = rs.getString(i);
System.out.println(rowData[i - 1]);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package br.com.certidoes.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.certidoes.classes.Certidao;
public class RepositorioCertidoesBD implements RepositorioCertidoes{
/**
* O nome do driver JDBC a ser usado na conexão.
*/
private String nomeDriver;
/**
* A url de conexão.
*/
private String urlConexao;
/**
* O usuário da conexão.
*/
private String usuarioConexao;
/**
* A senha do usuário da conexão.
*/
private String senhaConexao;
/**
* Flag que indica se o driver foi ou não carregado.
*/
private boolean indDriverCarregado;
/**
* Mensagem que indica falha na carga do driver.
*/
private static final String MSG_FALHA_CARGA_DRIVER =
"Nome do driver JDBC usado não corresponde a uma classe válida";
/**
* Mensagem que indica erro de obtenção da conexão com o banco de dados.
*/
private static final String MSG_ERRO_CONEXAO =
"Erro ao obter conexão com o banco de dados";
private static final String MSG_ERRO_ACESSO_BD =
"Erro de acesso ao banco de dados";
private static final String MSG_CERTIDAO_CADASTRADA =
"Certidao já cadastrada";
private static final String MSG_ID_NAO_ENCONTRADO =
"ID não encontrado";
private static final String MSG_ID_INVALIDO =
"ID inválido";
private static final String INSERT_CERTIDAO =
"INSERT INTO certidao (id, nome, DiasEmissao, Orgao_Emissor_cnpj) VALUES (?,?,?,?)";
private static final String PROCURA_CERT=
"SELECT id, nome, DiasEmissao, Orgao_Emissor_cnpj FROM certidao WHERE id = ?";
private static final String LISTA_CERT =
"SELECT id, nome, DiasEmissao, Orgao_Emissor_cnpj FROM certidao";
private static final String DELETE_CERT =
"DELETE FROM certidao WHERE id = ?";
/**
* O construtor da classe. Inicializa os parâmetros de conexão com o banco de dados.
*
* @param pNomeDriver o nome do driver.
* @param pUrlConexao a url de conexão com o banco.
* @param pUsuarioConexao o usuário da conexão.
* @param pSenhaConexao a senha da conexão.
*/
public RepositorioCertidoesBD(
String pNomeDriver,
String pUrlConexao,
String pUsuarioConexao,
String pSenhaConexao) {
super();
nomeDriver = pNomeDriver;
urlConexao = pUrlConexao;
usuarioConexao = pUsuarioConexao;
senhaConexao = pSenhaConexao;
indDriverCarregado = false;
}
private Connection getConexao() {
if (!indDriverCarregado) {
try {
Class.forName(nomeDriver);
indDriverCarregado = true;
} catch (ClassNotFoundException e) {
System.err.print(MSG_FALHA_CARGA_DRIVER);
}
}
try {
return DriverManager.getConnection(
urlConexao,
usuarioConexao,
senhaConexao);
} catch (SQLException e) {
System.err.print(MSG_ERRO_CONEXAO);
return null;
}
}
public void inserir(Certidao c) {
if (c != null) {
Connection con = getConexao();
PreparedStatement psCert = null;
PreparedStatement psEnd = null;
try {
psCert = con.prepareStatement(INSERT_CERTIDAO);
psCert.setInt(1, c.getId());
psCert.setString(2, c.getNome());
psCert.setString(3, c.getDiasEmissao());
psCert.setString(4, c.getOrgao_Emissor_cnpj());
psCert.executeUpdate();
} catch (SQLException e) {
System.err.print(e.getMessage());
} finally {
fechaRecursos(con, psCert, null);
fechaRecursos(con, psEnd, null);
}
}
}
public Certidao procurar(int id) {
if (id != 0) {
Connection con = getConexao();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(PROCURA_CERT);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
int bdId = rs.getInt(1);
String bdNome = rs.getString(2);
String bdDiasEmissao = rs.getString(3);
String bdOrgao_Emissor_cnpj = rs.getString(5);
Certidao cert = new Certidao();
cert.setId(bdId);
cert.setNome(bdNome);
cert.setDiasEmissao(bdDiasEmissao);
cert.setNome(bdOrgao_Emissor_cnpj);
return cert;
} else {
System.err.print(MSG_CERTIDAO_CADASTRADA);
}
} catch (SQLException e) {
System.err.println(MSG_ERRO_ACESSO_BD);
System.err.println(e.getMessage());
} finally {
fechaRecursos(con, ps, rs);
}
}
return null;
}
public ResultSet listar() {
Connection con = getConexao();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(LISTA_CERT);
rs = ps.executeQuery();
if (rs.next()){
return rs;
}
} catch (SQLException e) {
System.err.println(MSG_ERRO_ACESSO_BD);
System.err.println(e.getMessage());
}
return rs;
}
public void remover(int id) {
if (id != 0) {
Connection con = getConexao();
PreparedStatement ps = null;
try {
ps = con.prepareStatement(DELETE_CERT);
ps.setInt(1, id);
int rows = ps.executeUpdate();
if (rows <= 0) {
System.err.println("ID não encontrado");
}
} catch (SQLException e) {
System.err.println(MSG_ID_NAO_ENCONTRADO);
System.err.println(e.getMessage());
} finally {
fechaRecursos(con, ps, null);
}
} else {
System.err.println(MSG_ID_INVALIDO);
}
}
private void fechaRecursos(
Connection con,
PreparedStatement ps,
ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
@Override
public void cadastrar(Certidao c) {
// TODO Auto-generated method stub
}
}
Boa tarde!
Sou muito principiante e embrionária em java e em JDBC.
Por favor poderiam me ajudar:
Preciso fazer os inserts no banco com a aplicação em JAVA e quando vou executo a classe teste está dando o erro abaixo. Usei a arquitetura em camadas.
Erro ao obter conexão com o banco de dadosException in thread "main" java.lang.NullPointerException
at br.com.certidoes.jdbc.RepositorioCertidoesBD.listar(RepositorioCertidoesBD.java:183)
at br.com.certidoes.jdbc.CadastroCertidoes.listar(CadastroCertidoes.java:32)
at br.com.certidoes.jdbc.ConexionJDBC.listar(ConexionJDBC.java:54)
at br.com.certidoes.jdbc.TesteCertidoes.main(TesteCertidoes.java:21)
A classe teste e as demais seguem. O erro é no método listar, no qual anteriormente estava dando no método inserir. Alguém poderia me ajudar?? Agradeceria muito gente.
[code]package br.com.certidoes.jdbc;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import br.com.certidoes.classes.Certidao;
public class TesteCertidoes {
// @SuppressWarnings("deprecation")
public static void main(String[] args) {
Certidao certidao = new Certidao();
certidao.setId(12);
certidao.setNome("Alvara");
certidao.setDiasEmissao("4");
certidao.setOrgao_Emissor_cnpj("4657");
ConexionJDBC.obterInstancia().cadastrar(certidao);
// ConexionJDBC.obterInstancia().inserir(certidao);
ResultSet rs = ConexionJDBC.obterInstancia().listar();
ResultSetMetaData mdata;
try {
mdata = rs.getMetaData();
int colCount = mdata.getColumnCount();
String[] colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = mdata.getColumnName(i);
}
rs.beforeFirst();
while (rs.next()) {
String[] rowData = new String[colCount];
for (int i = 1; i <= colCount; i++) {
rowData[i - 1] = rs.getString(i);
System.out.println(rowData[i - 1]);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package br.com.certidoes.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.certidoes.classes.Certidao;
public class RepositorioCertidoesBD implements RepositorioCertidoes{
/**
* O nome do driver JDBC a ser usado na conexão.
*/
private String nomeDriver;
/**
* A url de conexão.
*/
private String urlConexao;
/**
* O usuário da conexão.
*/
private String usuarioConexao;
/**
* A senha do usuário da conexão.
*/
private String senhaConexao;
/**
* Flag que indica se o driver foi ou não carregado.
*/
private boolean indDriverCarregado;
/**
* Mensagem que indica falha na carga do driver.
*/
private static final String MSG_FALHA_CARGA_DRIVER =
"Nome do driver JDBC usado não corresponde a uma classe válida";
/**
* Mensagem que indica erro de obtenção da conexão com o banco de dados.
*/
private static final String MSG_ERRO_CONEXAO =
"Erro ao obter conexão com o banco de dados";
private static final String MSG_ERRO_ACESSO_BD =
"Erro de acesso ao banco de dados";
private static final String MSG_CERTIDAO_CADASTRADA =
"Certidao já cadastrada";
private static final String MSG_ID_NAO_ENCONTRADO =
"ID não encontrado";
private static final String MSG_ID_INVALIDO =
"ID inválido";
private static final String INSERT_CERTIDAO =
"INSERT INTO certidao (id, nome, DiasEmissao, Orgao_Emissor_cnpj) VALUES (?,?,?,?)";
private static final String PROCURA_CERT=
"SELECT id, nome, DiasEmissao, Orgao_Emissor_cnpj FROM certidao WHERE id = ?";
private static final String LISTA_CERT =
"SELECT id, nome, DiasEmissao, Orgao_Emissor_cnpj FROM certidao";
private static final String DELETE_CERT =
"DELETE FROM certidao WHERE id = ?";
/**
* O construtor da classe. Inicializa os parâmetros de conexão com o banco de dados.
*
* @param pNomeDriver o nome do driver.
* @param pUrlConexao a url de conexão com o banco.
* @param pUsuarioConexao o usuário da conexão.
* @param pSenhaConexao a senha da conexão.
*/
public RepositorioCertidoesBD(
String pNomeDriver,
String pUrlConexao,
String pUsuarioConexao,
String pSenhaConexao) {
super();
nomeDriver = pNomeDriver;
urlConexao = pUrlConexao;
usuarioConexao = pUsuarioConexao;
senhaConexao = pSenhaConexao;
indDriverCarregado = false;
}
private Connection getConexao() {
if (!indDriverCarregado) {
try {
Class.forName(nomeDriver);
indDriverCarregado = true;
} catch (ClassNotFoundException e) {
System.err.print(MSG_FALHA_CARGA_DRIVER);
}
}
try {
return DriverManager.getConnection(
urlConexao,
usuarioConexao,
senhaConexao);
} catch (SQLException e) {
System.err.print(MSG_ERRO_CONEXAO);
return null;
}
}
public void inserir(Certidao c) {
if (c != null) {
Connection con = getConexao();
PreparedStatement psCert = null;
PreparedStatement psEnd = null;
try {
psCert = con.prepareStatement(INSERT_CERTIDAO);
psCert.setInt(1, c.getId());
psCert.setString(2, c.getNome());
psCert.setString(3, c.getDiasEmissao());
psCert.setString(4, c.getOrgao_Emissor_cnpj());
psCert.executeUpdate();
} catch (SQLException e) {
System.err.print(e.getMessage());
} finally {
fechaRecursos(con, psCert, null);
fechaRecursos(con, psEnd, null);
}
}
}
public Certidao procurar(int id) {
if (id != 0) {
Connection con = getConexao();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(PROCURA_CERT);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
int bdId = rs.getInt(1);
String bdNome = rs.getString(2);
String bdDiasEmissao = rs.getString(3);
String bdOrgao_Emissor_cnpj = rs.getString(5);
Certidao cert = new Certidao();
cert.setId(bdId);
cert.setNome(bdNome);
cert.setDiasEmissao(bdDiasEmissao);
cert.setNome(bdOrgao_Emissor_cnpj);
return cert;
} else {
System.err.print(MSG_CERTIDAO_CADASTRADA);
}
} catch (SQLException e) {
System.err.println(MSG_ERRO_ACESSO_BD);
System.err.println(e.getMessage());
} finally {
fechaRecursos(con, ps, rs);
}
}
return null;
}
public ResultSet listar() {
Connection con = getConexao();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(LISTA_CERT);
rs = ps.executeQuery();
if (rs.next()){
return rs;
}
} catch (SQLException e) {
System.err.println(MSG_ERRO_ACESSO_BD);
System.err.println(e.getMessage());
}
return rs;
}
public void remover(int id) {
if (id != 0) {
Connection con = getConexao();
PreparedStatement ps = null;
try {
ps = con.prepareStatement(DELETE_CERT);
ps.setInt(1, id);
int rows = ps.executeUpdate();
if (rows <= 0) {
System.err.println("ID não encontrado");
}
} catch (SQLException e) {
System.err.println(MSG_ID_NAO_ENCONTRADO);
System.err.println(e.getMessage());
} finally {
fechaRecursos(con, ps, null);
}
} else {
System.err.println(MSG_ID_INVALIDO);
}
}
private void fechaRecursos(
Connection con,
PreparedStatement ps,
ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
@Override
public void cadastrar(Certidao c) {
// TODO Auto-generated method stub
}
}
Janaína Bandeira
Curtidas 0