Classe da Conexão com o banco de dados (Java DB):
package Formulário;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class ConectaBanco {
public Statement stm;//responsável por preparar e realizar pesquisas no banco de dados
public ResultSet rs;//responsável por amazenar o resultado de uma pesquisa passada para o Statement
private String driver = "apache_derby_net";//responsável por identificar o serviço de banco de dados
private String caminho = "jdbc:derby://localhost:1527/TestandoBanco";//responsável por setar o local do banco de dados
private String usuario = "Higor";
private String senha = "deliciacara15";
public Connection conn; // responsável por realizar a conexão com o banco de dados
public void conexao()
{//método responsável por realizar a conexão com o banco.
try {//tentativa inicial
System.setProperty("jdbc.Drivers", driver);//seta a propriedade do driver de conexão
conn = DriverManager.getConnection(caminho, usuario, senha);//realiza a conexão com o banco de dados.
JOptionPane.showMessageDialog(null, "Conectado com sucesso.");
} catch (SQLException ex) {//se não der certo... \/
Logger.getLogger(ConectaBanco.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Erro de conexão."
+"\nErro:"+ex.getMessage());
}
}
public void desconecta()
{//método para fechar a conexão com o banco de dados
try {
conn.close();//fecha a conexao
JOptionPane.showMessageDialog(null, "Conexão fechada com sucesso!");
} catch (SQLException ex) {
Logger.getLogger(ConectaBanco.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão."
+ "\nErro:"+ex.getMessage());
}
}
}
Classe principal (um JFrame):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Formulário;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FrmEstado extends javax.swing.JFrame {
ConectaBanco cb = new ConectaBanco();
int a = 20;
int b = 2;
public FrmEstado() {
super("Cadastro de estados.");
initComponents();
cb.conexao();
}
/**
* 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() {
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jRadioButton1 = new javax.swing.JRadioButton();
jPanel1 = new javax.swing.JPanel();
idde = new javax.swing.JLabel();
nde = new javax.swing.JLabel();
sde = new javax.swing.JLabel();
id = new javax.swing.JTextField();
nome = new javax.swing.JTextField();
sigla = new javax.swing.JTextField();
cadastrar = new javax.swing.JToggleButton();
formulario = new javax.swing.JLabel();
sair = new javax.swing.JLabel();
jFormattedTextField1.setText("jFormattedTextField1");
jRadioButton1.setText("jRadioButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
idde.setText("ID do estado:");
nde.setText("Nome do estado:");
sde.setText("Sigla do estado:");
id.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
idActionPerformed(evt);
}
});
nome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nomeActionPerformed(evt);
}
});
sigla.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
siglaActionPerformed(evt);
}
});
cadastrar.setText("Cadastrar");
cadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cadastrarActionPerformed(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()
.addGap(149, 149, 149)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(sde)
.addComponent(nde)
.addComponent(idde))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(id, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
.addComponent(nome)
.addComponent(sigla))
.addContainerGap(138, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cadastrar)
.addGap(183, 183, 183))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(idde)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nde)
.addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sde)
.addComponent(sigla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cadastrar)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
formulario.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
formulario.setText("Formulário de cadastro de estado");
sair.setText("Sair");
sair.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
sairMouseClicked(evt);
}
});
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.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(110, 110, 110)
.addComponent(formulario)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(sair)
.addGap(25, 25, 25))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(formulario, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sair))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void idActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void nomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void siglaActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void cadastrarActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == cadastrar) {
if (nome.getText().length() > a)//Limitando o caracteres de
//uma String pra 20.
{
try {
throw new Exception();
} catch (Exception ex) {
Logger.getLogger(FrmEstado.class.getName()).
log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Eroooooo");
}
}
if (sigla.getText().length() > b) {
try {
throw new Exception();
} catch (Exception ex) {
Logger.getLogger(FrmEstado.class.getName()).log(
Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "EROOOOO");
}
}
try {
PreparedStatement pst = cb.conn.prepareStatement("insert into "
+ "ESTADOS(NOME_DO_ESTADO,"
+ " SIGLA_DO_ESTADO)values(?,?)");
pst.setString(1, nome.getText());
pst.setString(2, sigla.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "DEU CERTO!");
} catch (SQLException ex) {
Logger.getLogger(FrmEstado.class.getName()).log(Level.SEVERE,
null, ex);
JOptionPane.showMessageDialog(null, "Num vai dá não!\nERRO:"
+ " " + ex);
}
}
}
private void sairMouseClicked(java.awt.event.MouseEvent evt) {
cb.desconecta();
System.exit(0);
}
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(FrmEstado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmEstado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmEstado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmEstado.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() {
new FrmEstado().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JToggleButton cadastrar;
private javax.swing.JLabel formulario;
private javax.swing.JTextField id;
private javax.swing.JLabel idde;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JLabel nde;
public javax.swing.JTextField nome;
private javax.swing.JLabel sair;
private javax.swing.JLabel sde;
public javax.swing.JTextField sigla;
// End of variables declaration
}