Olá, criei um código bem simples somente para conectar e cadastrar no banco de dados MySQL, e pelo código que fiz estou conseguindo conectar, no entanto, quando vou cadastrar aparece a mensagem java.lang.NullPointerException, alguém poderia me ajudar a resolver?
O código da Classe para conectar e cadastrar estão ai abaixo.
Classe de Conexão
package revisarcadastro;
import java.sql.*;
import javax.swing.JOptionPane;
public class ConexaoAnchieta {
String banco = "bancoTeste";
String usuario = "root";
String senha = "";
String host = "localhost";
Connection conexao;
Statement estado;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://"+host+":3306/"+banco;
public void conectar(){
try {
Class.forName(driver);
conexao = DriverManager.getConnection(url,usuario,senha);
Statement estado = conexao.createStatement();
System.out.println("Conectado");
} catch (Exception e) {
System.out.println("Falha ao conectar");
System.out.println(e);
}
}
public void cadastrar(String nome, int idade, String endereco, int codigo){
String sql = "insert into tabelaTeste (nome,idade,endereco,codigo) "
+ "values('"+nome+"',"+idade+",'"+endereco+"',"+codigo+");";
try {
int acao = estado.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"Cadastrado com sucesso");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Falha ao cadastrar");
JOptionPane.showMessageDialog(null,e);
}
}
}
Formulário Jframe
package revisarcadastro;
public class Cadastrar extends javax.swing.JFrame {
public Cadastrar() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
txtNome = new javax.swing.JTextField();
txtCodigo = new javax.swing.JTextField();
txtEndereco = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtIdade = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
btnCadastrar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(102, 102, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cadastro de compra e venda de carros ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
jPanel1.setForeground(new java.awt.Color(0, 0, 153));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 22, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(204, 255, 51));
jLabel4.setText("Código");
jLabel2.setText("Idade");
jLabel1.setText("Nome");
jLabel3.setText("Endereço");
btnCadastrar.setBackground(new java.awt.Color(102, 255, 0));
btnCadastrar.setText("Cadastrar ");
btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCadastrarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(134, 134, 134)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtNome)
.addComponent(txtIdade)
.addComponent(txtEndereco)
.addComponent(txtCodigo))
.addGap(102, 102, 102))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(217, Short.MAX_VALUE)
.addComponent(btnCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(194, 194, 194))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtIdade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(52, 52, 52)
.addComponent(btnCadastrar)
.addContainerGap(24, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
String nome = txtNome.getText();
int idade = Integer.parseInt(txtIdade.getText());
String endereco = txtEndereco.getText();
int cod = Integer.parseInt(txtCodigo.getText());
ConexaoAnchieta ca = new ConexaoAnchieta();
ca.conectar();
ca.cadastrar(nome,idade,endereco,cod);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Cadastrar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnCadastrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JTextField txtCodigo;
private javax.swing.JTextField txtEndereco;
private javax.swing.JTextField txtIdade;
private javax.swing.JTextField txtNome;
// End of variables declaration
}