Você está na página 1de 10

Tutorial Java SE com MySQL

Este tutorial apresenta o cdigo fonte da srie do tutorial de programao desktop utilizando a linguagem
de programao Java. O objetivo do tutorial facilitar o desenvolvimento de um bsico sistema desktop.
Segue a baixo e ferramentas utilizadas durante o desenvolvimento.

Link para video tutorial: https://www.youtube.com/watch?


v=o3aRbkyJUuM&list=PLf7vZ02bgXGXiiEFLE30kjEuH5wLtZrsI

Ferramentas:
Banco de Dados: Mysql
IDE: Eclipse JUNO
Plug-in IDE: WINDOWBUILDER
Verso Java: JRE6
Connector Mysql: mysql-connector-java-5.1.7-bin.jar

Obs*: O script auxilia apenas as vdeos aula de cadastro, atualizao e excluso de dados.

Segue abaixo os cdigos fonte da classe bin ClienteBin.java, classe conexao conexao.java,
classe control ClienteControl.java e as classesClienteGui.java e Principal.java

sistema.bin ClienteBin.java
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

package sistema.bin;
public class ClienteBin {
private
private
private
private
private
private

String
String
String
String
String
String

nome;
email;
telefone;
endereco;
cidade;
estado;

private int codigo;


public String getNome() {
return nome;
}

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

public void setNome(String nome) {


this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
}

sistema.conexao conexao.java
?

package sistema.conexao;

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class conexao {
Connection con;
private Connection oConn;
private Statement sStmt;
public conexao(){
}
public Connection abrirBDConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/banco";
con = DriverManager.getConnection(url,"root","aluno");
System.out.println("Conexao efetuada com sucesso");
return con;
}
catch(Exception e){
System.out.println("Erro ao abrir conexao com banco:");
e.printStackTrace();
return null;
}
}
public void fecharBDConn(){
try{
con.close();
System.out.println("Conexao finalizada com sucesso");
}catch(Exception e){
System.out.println("Erro ao fechar conexao com banco" + e.getMessage());
}
}
}

sistema.control ClienteControl.java
?

1
2
3
4
5
6
7
8
9
10
11

package sistema.control;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import sistema.bin.ClienteBin;
import sistema.conexao.conexao;
public class ClienteControl {

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

public void InsereDados(String nome,String email,String endereco,String telefone


conexao banco = new conexao();
String retorno = "erro";
try {
Connection ExConn = (Connection) banco.abrirBDConn();
Statement stmt = (Statement) ExConn.createStatement();
String sSQL = "INSERT INTO banco.cliente VALUES
(null,'"+nome+"','"+email+"','"+telefone+"','"+endereco+"','"+cidade+"'" +
",'"+estado+"');";
System.out.println(sSQL);
boolean res = stmt.execute(sSQL);

JOptionPane.showMessageDialog(null,(!res)?"Dados inseridos com sucesso!!!":""


"Os dados no puderam ser inseridos!!!");
stmt.close();
banco.fecharBDConn();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Os dados no puderam ser inseridos!!!");
}

public void ExcluirCliente(int codigo){


conexao banco = new conexao();
try {

Connection ExConn = (Connection) banco.abrirBDConn();


Statement stmt = (Statement) ExConn.createStatement();
String sSQL = "DELETE FROM banco.cliente WHERE idCliente = "+codigo+";";
boolean rs = stmt.execute(sSQL);
JOptionPane.showMessageDialog(null,(!rs)? "Dados do cliente excluidos com su
excluidos com sucesso.");
stmt.close();
banco.fecharBDConn();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Os dados no foram encontrado!!!");
}
}

public String AtualizarDados(String nome,String email,String endereco,String tel


ClienteBin CliBin){
conexao banco = new conexao();
String retorno = "erro";
int res;
try {
Connection ExConn = (Connection) banco.abrirBDConn();
Statement stmt = (Statement) ExConn.createStatement();

res = stmt.executeUpdate("UPDATE banco.cliente SET nome = '"+nome+"', enderec


"',estado = '"+estado+"',cidade = '"+cidade+"', telefone = '"+telefone+
"',email = '"+email+"' WHERE idCliente = "+CliBin.getCodigo());
if(res==1)JOptionPane.showMessageDialog(null,"Os dados foram atualizados com
stmt.close();
banco.fecharBDConn();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Os dados no puderam ser atualizados!!!"

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

}
return retorno;
}
public void BuscarDados(int codigo,ClienteBin CliBin) {
conexao banco = new conexao();
try {
Connection ExConn = (Connection) banco.abrirBDConn();
Statement stmt = (Statement) ExConn.createStatement();
String sSQL = "SELECT * FROM banco.cliente WHERE idCliente = "+codigo;
ResultSet rs = stmt.executeQuery(sSQL);

while(rs.next())
{
CliBin.setCodigo(rs.getInt("idCliente"));
CliBin.setNome(rs.getString("nome"));
CliBin.setEndereco(rs.getString("endereco"));
CliBin.setEstado(rs.getString("estado"));
CliBin.setCidade(rs.getString("cidade"));
CliBin.setTelefone(rs.getString("telefone"));
CliBin.setEmail(rs.getString("email"));
}
stmt.close();
banco.fecharBDConn();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Os dados no puderam ser encontrado!!!")
}

}
}

sistema.gui ClienteGui.java
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package sistema.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import
import
import
import
import
import
import
import

javax.swing.JFrame;
javax.swing.JOptionPane;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.JLabel;
java.awt.Font;
javax.swing.JTextField;
javax.swing.JButton;

import sistema.bin.ClienteBin;
import sistema.control.ClienteControl;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ClienteGui extends JFrame {

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

private
private
private
private
private
private
private

JPanel contentPane;
JTextField jtfNome;
JTextField jtfEmail;
JTextField jtfTelefone;
JTextField jtfEndereco;
JTextField jtfCidade;
JTextField jtfEstado;

ClienteControl CliControl = new ClienteControl();


ClienteBin CliBin = new ClienteBin();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClienteGui frame = new ClienteGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public ClienteGui() {
setTitle("Cliente");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 509, 365);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Cadastro de Clientes");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblNewLabel.setBounds(27, 11, 233, 45);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Nome:");
lblNewLabel_1.setBounds(27, 79, 46, 14);
contentPane.add(lblNewLabel_1);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(27, 104, 46, 14);
contentPane.add(lblEmail);
JLabel lblTelefone = new JLabel("Telefone:");
lblTelefone.setBounds(27, 129, 71, 14);
contentPane.add(lblTelefone);

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

JLabel lblEndereco = new JLabel("Endereco:");


lblEndereco.setBounds(27, 156, 71, 14);
contentPane.add(lblEndereco);
JLabel lblCidade = new JLabel("Cidade:");
lblCidade.setBounds(27, 181, 46, 14);
contentPane.add(lblCidade);
JLabel lblEstado = new JLabel("Estado:");
lblEstado.setBounds(27, 206, 46, 14);
contentPane.add(lblEstado);
jtfNome = new JTextField();
jtfNome.setBounds(117, 76, 351, 20);
contentPane.add(jtfNome);
jtfNome.setColumns(10);
jtfEmail = new JTextField();
jtfEmail.setColumns(10);
jtfEmail.setBounds(117, 101, 351, 20);
contentPane.add(jtfEmail);
jtfTelefone = new JTextField();
jtfTelefone.setColumns(10);
jtfTelefone.setBounds(117, 126, 351, 20);
contentPane.add(jtfTelefone);
jtfEndereco = new JTextField();
jtfEndereco.setColumns(10);
jtfEndereco.setBounds(117, 153, 351, 20);
contentPane.add(jtfEndereco);
jtfCidade = new JTextField();
jtfCidade.setColumns(10);
jtfCidade.setBounds(117, 178, 351, 20);
contentPane.add(jtfCidade);
jtfEstado = new JTextField();
jtfEstado.setColumns(10);
jtfEstado.setBounds(117, 203, 351, 20);
contentPane.add(jtfEstado);
JButton btnCadastrar = new JButton("Cadastrar");
btnCadastrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String nome = jtfNome.getText();
String email = jtfEmail.getText();
String endereco = jtfEndereco.getText();
String telefone = jtfTelefone.getText();
String cidade = jtfCidade.getText();
String estado = jtfEstado.getText();
CliControl.InsereDados(nome,email,telefone,endereco,cidade,estado);
}

});

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

btnCadastrar.setBounds(375, 249, 97, 23);


contentPane.add(btnCadastrar);
JButton btnLimpar = new JButton("Limpar");
btnLimpar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jtfNome.setText("");
jtfEmail.setText("");
jtfTelefone.setText("");
jtfEndereco.setText("");
jtfCidade.setText("");
jtfEstado.setText("");
}
});
btnLimpar.setBounds(71, 249, 89, 23);
contentPane.add(btnLimpar);

JButton btnExcluir = new JButton("Excluir");


btnExcluir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int codigo = Integer.parseInt(JOptionPane.showInputDialog(null,"Digite o codi
"));
CliControl.ExcluirCliente(codigo);
}
});
btnExcluir.setBounds(276, 249, 89, 23);
contentPane.add(btnExcluir);

JButton btnAtualizaer = new JButton("Atualizar");


btnAtualizaer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CliControl.AtualizarDados(jtfNome.getText(), jtfEmail.getText(), jtfEndereco
jtfTelefone.getText(), jtfCidade.getText(), jtfEstado.getText(), CliBin);
}
});
btnAtualizaer.setBounds(171, 249, 89, 23);
contentPane.add(btnAtualizaer);

JButton btnBuscar = new JButton("Buscar");


btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int codigo = Integer.parseInt(JOptionPane.showInputDialog(null,"Digite o codi
"));
CliControl.BuscarDados(codigo,CliBin);
jtfNome.setText(CliBin.getNome());
jtfEmail.setText(CliBin.getEmail());
jtfTelefone.setText(CliBin.getTelefone());
jtfEndereco.setText(CliBin.getEndereco());
jtfCidade.setText(CliBin.getCidade());
jtfEstado.setText(CliBin.getEstado());
}
});
btnBuscar.setBounds(379, 283, 89, 23);
contentPane.add(btnBuscar);
JButton btnSair = new JButton("Sair");
btnSair.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();

170
171
172
173
174

}
});
btnSair.setBounds(286, 283, 89, 23);
contentPane.add(btnSair);
}

sistema.gui Principal.java
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

package sistema.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import
import
import
import
import
import
import
import

javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.JMenuBar;
javax.swing.JMenu;
javax.swing.JMenuItem;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;

public class Principal extends JFrame {


private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Principal frame = new Principal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Principal() {
setTitle("Tela Principal");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 574, 336);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnGerenciamento = new JMenu("Gerenciamento");
menuBar.add(mnGerenciamento);

42
43
44
45
46
47
48
49
50
51
52
53

JMenuItem mntmCliente = new JMenuItem("Cliente");


mntmCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new ClienteGui().setVisible(true);
}
});
mnGerenciamento.add(mntmCliente);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}

Você também pode gostar