Bom amigo, fiz um exemplo básico de testes, pois a melhor maneira de vc entender é ver um exemplo funcionando, lembre-se que fiz correndo e não cerquei erros ou coisas assim, só o básico mesmo, em Java SE, cria o pacote chamado teste2 e testa pra vc ver ele funcionando:
- Um factory para conexões com singleton, olha aí: Nome do arquivo::ConnectionFactory.java
package teste2;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author xjunior
*/
public class ConnectionFactory {
private static Connection instance=null;
private static int banck=0;
final static int B_MYSQL = 0;
private ConnectionFactory() throws SQLException{
try {
switch(ConnectionFactory.banck){
case B_MYSQL:
Class.forName("com.mysql.jdbc.Driver");
ConnectionFactory.instance=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/teste","root","");
break;
}
}
catch (ClassNotFoundException e){
throw new SQLException(e.getMessage());
}
}
public static Connection getConnection(int TypeBanck) throws SQLException{
if(ConnectionFactory.instance==null || ConnectionFactory.banck!=TypeBanck){
ConnectionFactory.banck=TypeBanck;
new ConnectionFactory();
}
return ConnectionFactory.instance;
}
}
Um beans chamado Testes (pq a tabela chama testes)::Nome do arquivo::Testes.java
package teste2;
/**
*
* @author xjunior
*/
public class Testes {
private int _codigo;
private String _nome;
/**
* @return the _codigo
*/
public int getCodigo() {
return _codigo;
}
/**
* @param codigo the _codigo to set
*/
public Testes setCodigo(int codigo) {
this._codigo = codigo;
return this;
}
/**
* @return the _nome
*/
public String getNome() {
return _nome;
}
/**
* @param nome the _nome to set
*/
public Testes setNome(String nome) {
this._nome = nome;
return this;
}
}
Um DAO da Tabela Testes::Nome do arquivo::TestesDAO:
package teste2;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author xjunior
*/
public class TestesDAO {
private Connection connection;
public TestesDAO() throws SQLException{
this.connection = ConnectionFactory.getConnection(ConnectionFactory.B_MYSQL);
}
/**
*
* @param testes testes
* @return TestesDAO
* @throws SQLException
*/
public TestesDAO addTestes(Testes testes) throws SQLException{
String sql = "insert into testes (nome) values (?)";
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
try{
stm.setString(1, testes.getNome());
stm.execute();
JOptionPane.showMessageDialog(null, "Gravado Com suscesso!!!");
}catch(SQLException e){
this.connection.close();
throw new SQLException(e);
}
finally{
stm.close();
}
return this;
}
public List<Testes> searchTestes() throws SQLException{
String sql = "select * from testes";
List<Testes> teste = new ArrayList<Testes>();
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
ResultSet result = stm.executeQuery();
while(result.next()){
Testes test = new Testes();
test.setCodigo(Integer.parseInt(result.getString("codigo"))).setNome(result.getString("nome"));
teste.add(test);
}
return teste;
}
public List<Testes> searchTestes(String nome) throws SQLException{
List<Testes> teste = new ArrayList<Testes>();
try{
String sql = "select * from testes where nome like ?";
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
stm.setString(1,nome);
ResultSet result = stm.executeQuery();
while(result.next()){
Testes test = new Testes();
test.setCodigo(Integer.parseInt(result.getString("codigo"))).setNome(result.getString("nome"));
teste.add(test);
}
stm.close();
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
finally{
return teste;
}
}
public List<Testes> searchTestes(int codigo) throws SQLException{
List<Testes> teste = new ArrayList<Testes>();
try{
String sql = "select * from testes where codigo = ?";
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
stm.setInt(1,codigo);
ResultSet result = stm.executeQuery();
while(result.next()){
Testes test = new Testes();
test.setCodigo(Integer.parseInt(result.getString("codigo"))).setNome(result.getString("nome"));
teste.add(test);
}
stm.close();
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
finally{
return teste;
}
}
public void updateTestes(Testes testes) throws SQLException{
try{
String sql="UPDATE testes SET nome = ? WHERE codigo = ?";
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
stm.setString(1, testes.getNome());
stm.setInt(2, testes.getCodigo());
stm.execute();
stm.close();
JOptionPane.showMessageDialog(null,"Atualizado Com Sucesso!!!");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Ocorreu um erro ao atualizar!!!");
}
}
public void removeTestes(Testes testes) throws SQLException{
try{
String sql="DELETE FROM testes WHERE codigo = ?";
PreparedStatement stm = (PreparedStatement) this.connection.prepareStatement(sql);
stm.setInt(1, testes.getCodigo());
stm.execute();
stm.close();
JOptionPane.showMessageDialog(null,"Posição "+testes.getCodigo()+" removida com Sucesso!!!");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Ocorreu um erro ao remover posição!!!");
}
}
}
E o main::Nome do arquivo::Main.java
package teste2;
import java.sql.SQLException;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author xjunior
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
TestesDAO connect = new TestesDAO();
int condition=1;
while(condition==1){
String str = "Escolha \n 1->Inserir\n 2->Visualizar Todos\n 3->Pesquisar por Nome(inserir % para estar entre)\n 4->Pesquisar por Código\n 5->Atualizar Testes por Código\n 6->Remover Testes por Código\n "; switch(Integer.parseInt(JOptionPane.showInputDialog(str))){
case 1:
do{
Main.insertElement(connect);
}while(JOptionPane.showConfirmDialog(null, "Deseja Inserir Outro Nome?")==0);
break;
case 2:
Main.searchElement(connect);
break;
case 3:
Main.searchNome(connect);
break;
case 4:
Main.searchCodigo(connect);
break;
case 5:
Main.updateTestes(connect);
break;
case 6:
Main.removeTestes(connect);
break;
default:
JOptionPane.showMessageDialog(null, "Você inseriu uma opção incorreta!!!");
break;
}
condition = JOptionPane.showConfirmDialog(null, "Deseja Finalizar o aplicativo?");
}
}
public static void insertElement(TestesDAO connect) throws SQLException{
try{
Testes testes = new Testes();
testes.setNome(JOptionPane.showInputDialog("Insira o nome do testes:"));
connect.addTestes(testes);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
public static void searchElement(TestesDAO connect) throws SQLException{
List<Testes> teste = connect.searchTestes();
Main.listTestes(teste);
}
public static void searchNome(TestesDAO connect) throws SQLException{
List<Testes> teste = connect.searchTestes(JOptionPane.showInputDialog("insira uma parte do nome a ser buscado:"));
Main.listTestes(teste);
}
public static void searchCodigo(TestesDAO connect) throws SQLException{
List<Testes> teste = connect.searchTestes(Integer.parseInt(JOptionPane.showInputDialog("insira o código do Testes:")));
Main.listTestes(teste);
}
public static void listTestes(List<Testes> teste){
String str = "";
for(Testes test : teste){
str+="Código: "+test.getCodigo()+" | Nome: "+test.getNome()+"\n";
}
JOptionPane.showMessageDialog(null, str);
}
public static void updateTestes(TestesDAO connect) throws SQLException{
try{
Testes testes = new Testes();
testes.setCodigo(Integer.parseInt(JOptionPane.showInputDialog("Insira a posição que deseja atualizar:")));
testes.setNome(JOptionPane.showInputDialog("Insira o nome para atualização:"));
connect.updateTestes(testes);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
public static void removeTestes(TestesDAO connect) throws SQLException{
try{
Testes testes = new Testes();
testes.setCodigo(Integer.parseInt(JOptionPane.showInputDialog("Insira a posição que deseja remover:")));
connect.removeTestes(testes);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
}
E a tabela do banco de dados pra vc testar:
--
-- Estrutura da tabela `testes`
--
CREATE TABLE IF NOT EXISTS `testes` (
`codigo` int(11) NOT NULL auto_increment,
`nome` varchar(50) NOT NULL,
PRIMARY KEY (`codigo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
Espero ter ajudado…