Ir ao conteúdo
  • Cadastre-se

Erro ao Inserir dados


Ramalho Junior

Posts recomendados

Olá pessoal

Estou com a seguinte duvida estou criando um formulario simples para cadastrar estado pois quando vou inserir os dado aparece os seguintes erros:

ERRO2! Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

at dao.EstadoDao.salvar(EstadoDao.java:33)

at view.EstadoView.btnCadastrarActionPerformed(EstadoView.java:120)

at view.EstadoView.access$000(EstadoView.java:14)

at view.EstadoView$1.actionPerformed(EstadoView.java:54)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)

at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)

at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)

at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)

at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

at java.awt.Component.processMouseEvent(Component.java:6505)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)

at java.awt.Component.processEvent(Component.java:6270)

at java.awt.Container.processEvent(Container.java:2229)

at java.awt.Component.dispatchEventImpl(Component.java:4861)

at java.awt.Container.dispatchEventImpl(Container.java:2287)

at java.awt.Component.dispatchEvent(Component.java:4687)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)

at java.awt.Container.dispatchEventImpl(Container.java:2273)

at java.awt.Window.dispatchEventImpl(Window.java:2713)

at java.awt.Component.dispatchEvent(Component.java:4687)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)

at java.awt.EventQueue.access$000(EventQueue.java:101)

at java.awt.EventQueue$3.run(EventQueue.java:666)

at java.awt.EventQueue$3.run(EventQueue.java:664)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)

at java.awt.EventQueue$4.run(EventQueue.java:680)

at java.awt.EventQueue$4.run(EventQueue.java:678)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:121)

at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:182)

at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:221)

at java.security.AccessController.doPrivileged(Native Method)

at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:219)

at java.awt.Dialog.show(Dialog.java:1072)

at java.awt.Component.show(Component.java:1651)

at java.awt.Component.setVisible(Component.java:1603)

at java.awt.Window.setVisible(Window.java:1013)

at java.awt.Dialog.setVisible(Dialog.java:1003)

at view.EstadoView$2.run(EstadoView.java:167)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)

at java.awt.EventQueue.access$000(EventQueue.java:101)

at java.awt.EventQueue$3.run(EventQueue.java:666)

at java.awt.EventQueue$3.run(EventQueue.java:664)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

SEGUE ABAIXO TODAS AS CLASSES



public class Estado {

private Integer idEstado;
private String nome;


public Integer getIdEstado(){
return idEstado;
}


public void setIdEstado(Integer idEstado){
this.idEstado = idEstado;
}


public String getNome(){
return nome;
}


public void setNome(String nome){
this.nome = nome;
}

}


ESTADODAO
package dao;
import bean.Estado;
import com.mysql.jdbc.PreparedStatement;
import java.sql.SQLException;
import util.Conexao;

//import java.util.ArrayList;
//import java.util.List;

/**
*
* @author Antonio
*/
public class EstadoDao implements InterfaceDao<Estado> {

@Override
public boolean salvar(Estado bean){

Conexao conexao = new Conexao();
boolean result = true;
PreparedStatement ps = null;

String sql = "INSERT INTO estado (nomeEstado) VALUES (?)";

conexao.conectar();

try{

ps = (PreparedStatement) conexao.connection.prepareStatement(sql);
ps.setString(1, bean.getNome().toUpperCase());
ps.executeUpdate();
ps.close();
conexao.connection.close();

}catch(SQLException ex){
System.out.println("ERRO: 1" + ex.getMessage());
result = false;
}finally{

conexao = null;
System.gc();

}

return result;

}

}


INTERFACEDAO
public interface InterfaceDao<T> {

public boolean salvar(T bean);

}


CONEXAO
package util;
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 Ramalho Junior
*/
public class Conexao {

private String DRIVER;
private String USER;
private String SENHA;
private String URL;
public Connection connection;
public Statement statement;
public ResultSet resultSet;

public Conexao(){
URL = "jdbc:mysql://localhost:3360/cadcidades";
DRIVER = "com.mysql.jdbc.Driver";
USER = "root";
SENHA = "bequick";
}

public void conectar(){

try{
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, SENHA);
}catch(ClassNotFoundException ex){

JOptionPane.showMessageDialog(null, "APLICAÇÃO NÃO ENCONTROU A "

+ "BASE DE DADOS! \n" +
"POR FAVOR! PROCURE A ADMINISTRADOR DO SISTEMA."

);

System.out.println("ERRO1! " + ex.getMessage());

}catch(SQLException ex){

System.out.println("ERRO2! " + ex.getMessage());

}

}

public void executeQuery(String sql){

try{

statement = connection.createStatement(

ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY

);

resultSet = statement.executeQuery(sql);

}catch(SQLException ex){

JOptionPane.showMessageDialog(null, ex.getMessage());

}

}

}



ESTADOVIEW
package view;
import bean.Estado;
import dao.EstadoDao;
import javax.swing.JOptionPane;

/**
*
* @author Antonio
*/
public class EstadoView extends javax.swing.JDialog {

private Estado estado;
private EstadoDao estadoDao;

public EstadoView(java.awt.Frame parent, boolean modal){

super(parent, modal);
initComponents();
estadoDao = new EstadoDao();

}

/**
* 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();
jLabel1 = new javax.swing.JLabel();
tfNomeEstado = new javax.swing.JTextField();
btnCadastrar = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dados Cadastrais", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.black));
jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jPanel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel1.setText("Nome Estado:");

btnCadastrar.setText("Cadastrar");
btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCadastrarActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfNomeEstado))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnCadastrar)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfNomeEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCadastrar)
.addContainerGap(34, Short.MAX_VALUE))
);

jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("CADASTRO DE ESTADOS");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(174, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(170, 170, 170))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(19, 19, 19)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(215, Short.MAX_VALUE))
);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-516)/2, (screenSize.height-438)/2, 516, 438);
}// </editor-fold>

private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
// CADASTRAR ESTADOS
estado = new Estado();
estado.setNome(tfNomeEstado.getText());
if(estadoDao.salvar(estado)){
JOptionPane.showMessageDialog(null, "DADOS CADASTRADOS COM SUCESSO!");
tfNomeEstado.setText("");
tfNomeEstado.requestFocus();
}else{
JOptionPane.showMessageDialog(null, "ERRO! POR FAVOR TENTE MAIS TARDE!");
}
}

/**
* @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 [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
*/
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(EstadoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EstadoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EstadoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EstadoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
EstadoView dialog = new EstadoView(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {

@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.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.JPanel jPanel1;
private javax.swing.JTextField tfNomeEstado;
// End of variables declaration
}
ESTADO

Que erro pode estar acontecendo?

Link para o comentário
Compartilhar em outros sites

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...