Consulta Base de Dados mysql

Olá Pessoal essa classe é para acessar banco de dados mysql, criei um frame, alguns botões para fazer a consulta, compila sem achar erros, mas na execução dá erro acho que é na sintaxe do Mysql.

Obrigado a todos!

Obs. Meu SO é Linux (Ubuntu) e IDE netbeans.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.;
import javax.swing.
;
import java.awt.*;

public class MoveRegistros extends JFrame implements ActionListener {
JLabel l1,l2,l3,l4,l5,l6,l7;
JButton b1,b2,b3,b4,b5,b6;
JTextField tfCodigo,tfNome,tfAdmissao,tfDemissao,tfFuncao,tfSexo;

JPanel p1 = new JPanel();
ResultSet rs;

 public static void main(String[] args) {

JFrame Janela = new MoveRegistros();
Janela.setVisible(true);
WindowListener x = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
Janela.addWindowListener(x);

 }

public MoveRegistros() {

p1.setLayout(new FlowLayout (FlowLayout.CENTER));
l1 = new JLabel (“Codigo”);
l2 = new JLabel (“Nome”);
l3 = new JLabel (“Admissao”);
l4 = new JLabel (“Demissao”);
l5 = new JLabel (“Funcao”);
l6 = new JLabel (“Sexo”);
l7 = new JLabel ("");

for(int i=0;i<=60;i++)

l7.setText(l7.getText()+"");
tfCodigo = new JTextField(3);
tfCodigo.setEditable(false);
tfNome = new JTextField(50);
tfNome.setEditable(false);
tfAdmissao = new JTextField(10);
tfAdmissao.setEditable(false);
tfDemissao = new JTextField(10);
tfDemissao.setEditable(false);
tfFuncao = new JTextField(50);
tfFuncao.setEditable(false);
tfSexo = new JTextField(1);
tfSexo.setEditable(false);
b1 = new JButton(“Próximo”);
b2 = new JButton(“Anterior”);
b3 = new JButton(“Primeiro”);
b4 = new JButton(“Último”);
b5 = new JButton("+ 10 Registros");
b6 = new JButton("- 10 Registros");
b1.setBackground(new Color(180,180,250));
b2.setBackground(new Color(180,180,250));
b3.setBackground(new Color(180,180,250));
b4.setBackground(new Color(180,180,250));
b5.setBackground(new Color(180,180,250));
b6.setBackground(new Color(180,180,250));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
p1.add(l1); p1.add(tfCodigo);
p1.add(l2); p1.add(tfNome);
p1.add(l3); p1.add(tfAdmissao);
p1.add(l4); p1.add(tfDemissao);
p1.add(l5); p1.add(tfFuncao);
p1.add(l6); p1.add(tfSexo);
p1.add(l7);
p1.add(b1);
p1.add(b2);
p1.add(b3);
p1.add(b4);
p1.add(b5);
p1.add(b6);
getContentPane().add(p1);
setTitle(“Tabela de Funcionários da Labordental LTDA”);
setSize(900,200);
setResizable(false);

Connection conn = null;
String teste = “SELECT * FROM FUNCIONARIOS;”;
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection( “jdbc:mysql://localhost/labordental?user=root” );
JOptionPane.showMessageDialog(null,“Estabelecendo Conexão…”,“Conectando”,1);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(teste);

        rs.first();
        atualizaCampos();

}
catch(ClassNotFoundException e) {
JOptionPane.showMessageDialog(null,“Excessão Classe não encontrada”,“Conexão Falhou”,2);
e.printStackTrace();
}
catch(SQLException e) {
JOptionPane.showMessageDialog(null,“SQL Exception… Erro na consulta”,“Conexão Falhou”,2);
e.printStackTrace();
}
}

public void actionPerformed (ActionEvent e) {
    
    try{

if (e.getSource()==b1)
rs.next();
if (e.getSource()==b2)
rs.previous();
if (e.getSource()==b3)
rs.first();
if (e.getSource()==b4)
rs.last();
if (e.getSource()==b5)
rs.relative(10);
if (e.getSource()==b6)
rs.relative(-10);

atualizaCampos();

}   
    
  catch(SQLException erro) {
            JOptionPane.showMessageDialog(null,"Erro no Banco de Dados","Erro",2);
            erro.printStackTrace();
 }
} 

public void atualizaCampos(){

try {

tfCodigo.setText(rs.getString(“CODIGO”));
tfNome.setText(rs.getString(“NOME”));
tfAdmissao.setText(rs.getString(“ADMISSAO”));
tfDemissao.setText(rs.getString(“DEMISSAO”));
tfFuncao.setText(rs.getString(“FUNCAO”));
tfSexo.setText(rs.getString(“SEXO”));

}

catch(SQLException erro) {
            JOptionPane.showMessageDialog(null,"Erro no Banco de Dados","Erro",2);
            erro.printStackTrace();
}

}
}

Qual o Stack Trace do erro? Seu código e muito grande, fica mais fácil sabendo qual erro está dando… A sua URL no método DriverManager.getConnection parece estranha, mas como aqui uso postgres não sei dizer… Seria legal ver a exceção para saber o que está acontecendo…

Tire o “;” que está no final da sua instrução SQL.

Tire o “;” que está no final da sua instrução SQL. O correto é:

 String teste = &quot;SELECT * FROM FUNCIONARIOS&quot;; 

Prezado colega,

Peguei o seu código e fiz a correção conforme informado pelo nosso amigo acima mas mesmo assim, embora a sintaxe da instrução esteja correta, ainda dá erro na consulta SQL.
No meu caso, eu modifiquei as linhas referentes ao banco de dados pois estou usando o access. Não consegui descobrir qual é o erro

Atenciosamente,

Edson

Caríssimos,

Pelo que entendi do código, parece que não há uma maneira de se navegar entre os registros. Eu estou usando o banco de dados access e o programa compila direitinho sem problemas mas quando vou executar, ele da a mensagem de erro e cria a tela mas não carrega os dados do banco.

Nos ajeudem se for o caso!!

Obrigado!!
Edson

Neste caso repito as palavras do colega Bruno… postem os erros que vos acontecem e com certeza isso dará pistas mais claras do problema.

Caro Ademilton e demais colegas,

Peguei o código de nosso amigo Baleeiro e fiz algumas alterações tentando ajudar na solução do problema encontrado por ele.

Mudei o banco de adados para o Access e Adaptei alguma coisinha. O programa compilou sem problemas e ao tentar executá-lo, ele dá a mensagem solicitada na linha 133 conforme:
“JOptionPane.showMessageDialog(null,“SQL Exception… Erro na consulta”,“Conexão Falhou”,2);”. Ao clicar nesta mensagem, o programa abre a tela mas não carrega os registros cadastrados no banco.

Apresenta esta mensagem:
Exception in thread “main” java.Lang.NullPointerException
at MoveRegistros.atualizaCampos(MoveRegistros.java:168)
at MoveRegistros.<init>(MoveRegistros.java:126)
at MoveRegistros.main(MoveRegistros.java:24)

O que pode estar acontecendo? Segue abaixo, o código inteirinho na íntegra:


//import java.awt.event.ActionEvent; 
//import java.awt.event.ActionListener; 
//import java.awt.event.WindowAdapter; 
//import java.awt.event.WindowEvent; 
//import java.awt.event.WindowListener; 
import java.sql.*; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*;

//Consulta base de dados mysql - PJ avançado

public class MoveRegistros extends JFrame implements ActionListener &#123; 

	JLabel l1,l2,l3,l4,l5,l6,l7; 
	JButton b1,b2,b3,b4,b5,b6; 
	JTextField tfCodigo,tfNome,tfAdmissao,tfDemissao,tfFuncao,tfSexo; 

	JPanel p1 = new JPanel&#40;&#41;; 
	ResultSet rs; 

public static void main&#40;String&#91;&#93; args&#41; &#123; 

	JFrame Janela = new MoveRegistros&#40;&#41;; 
	Janela.setVisible&#40;true&#41;; 
	WindowListener x = new WindowAdapter&#40;&#41; 
&#123; 
public void windowClosing&#40;WindowEvent e&#41; 
	&#123; 
		System.exit&#40;0&#41;; 
	&#125; 
&#125;; 

	Janela.addWindowListener&#40;x&#41;; 

&#125; 

public MoveRegistros&#40;&#41; &#123; 

	p1.setLayout&#40;new FlowLayout &#40;FlowLayout.CENTER&#41;&#41;; 
	l1 = new JLabel &#40;&quot;Codigo&quot;&#41;; 
	l2 = new JLabel &#40;&quot;Nome&quot;&#41;; 
	l3 = new JLabel &#40;&quot;Admissao&quot;&#41;; 
	l4 = new JLabel &#40;&quot;Demissao&quot;&#41;; 
	l5 = new JLabel &#40;&quot;Funcao&quot;&#41;; 
	l6 = new JLabel &#40;&quot;Sexo&quot;&#41;; 
	l7 = new JLabel &#40;&quot;&quot;&#41;; 

for&#40;int i=0;i&lt;=60;i++&#41; 

	l7.setText&#40;l7.getText&#40;&#41;+&quot;&quot;&#41;; 
	tfCodigo = new JTextField&#40;3&#41;; 
	tfCodigo.setEditable&#40;false&#41;; 
	tfNome = new JTextField&#40;50&#41;; 
	tfNome.setEditable&#40;false&#41;; 
	tfAdmissao = new JTextField&#40;10&#41;; 
	tfAdmissao.setEditable&#40;false&#41;; 
	tfDemissao = new JTextField&#40;10&#41;; 
	tfDemissao.setEditable&#40;false&#41;; 
	tfFuncao = new JTextField&#40;50&#41;; 
	tfFuncao.setEditable&#40;false&#41;; 
	tfSexo = new JTextField&#40;1&#41;; 
	tfSexo.setEditable&#40;false&#41;; 
		
	b1 = new JButton&#40;&quot;Próximo&quot;&#41;; 
	b2 = new JButton&#40;&quot;Anterior&quot;&#41;; 
	b3 = new JButton&#40;&quot;Primeiro&quot;&#41;; 
	b4 = new JButton&#40;&quot;Último&quot;&#41;; 
	b5 = new JButton&#40;&quot;+ 10 Registros&quot;&#41;; 
	b6 = new JButton&#40;&quot;- 10 Registros&quot;&#41;; 
		
	b1.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
	b2.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
	b3.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
	b4.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
	b5.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
	b6.setBackground&#40;new Color&#40;180,180,250&#41;&#41;; 
		
	b1.addActionListener&#40;this&#41;; 
	b2.addActionListener&#40;this&#41;; 
	b3.addActionListener&#40;this&#41;; 
	b4.addActionListener&#40;this&#41;; 
	b5.addActionListener&#40;this&#41;; 
	b6.addActionListener&#40;this&#41;;
	 
	p1.add&#40;l1&#41;; p1.add&#40;tfCodigo&#41;; 
	p1.add&#40;l2&#41;; p1.add&#40;tfNome&#41;; 
	p1.add&#40;l3&#41;; p1.add&#40;tfAdmissao&#41;; 
	p1.add&#40;l4&#41;; p1.add&#40;tfDemissao&#41;; 
	p1.add&#40;l5&#41;; p1.add&#40;tfFuncao&#41;; 
	p1.add&#40;l6&#41;; p1.add&#40;tfSexo&#41;; 
		
	p1.add&#40;l7&#41;; 
	p1.add&#40;b1&#41;; 
	p1.add&#40;b2&#41;; 
	p1.add&#40;b3&#41;; 
	p1.add&#40;b4&#41;; 
	p1.add&#40;b5&#41;; 
	p1.add&#40;b6&#41;;
	 
	getContentPane&#40;&#41;.add&#40;p1&#41;; 
	setTitle&#40;&quot;Tabela de Funcionários da Labordental LTDA&quot;&#41;; 
	setSize&#40;900,200&#41;; 
	setResizable&#40;false&#41;; 


Connection conn; // = null; 
//String teste = &quot;SELECT * FROM FUNCIONARIOS&quot;; 
try &#123; 
Class.forName&#40;&quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;&#41;; 
conn = DriverManager.getConnection&#40; &quot;jdbc&#58;odbc&#58;Empresa&quot;, &quot;&quot;,&quot;&quot; &#41;; 
JOptionPane.showMessageDialog&#40;null,&quot;Estabelecendo Conexão...&quot;,&quot;Conectando&quot;,1&#41;; 

 		Statement stm = conn.createStatement&#40;
 		ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY&#41;;
 		ResultSet rs = stm.executeQuery&#40;&quot;SELECT * FROM FUNCIONARIOS&quot;&#41;;



	//Statement stm = conn.createStatement&#40;&#41;; 
	//ResultSet rs = stm.executeQuery&#40;&quot;SELECT * FROM FUNCIONARIOS&quot;&#41;;
//ResultSet rs = stm.executeQuery&#40;teste&#41;; 


rs.first&#40;&#41;; 
atualizaCampos&#40;&#41;; 
&#125; 
catch&#40;ClassNotFoundException e&#41; &#123; 
JOptionPane.showMessageDialog&#40;null,&quot;Excessão Classe não encontrada&quot;,&quot;Conexão Falhou&quot;,2&#41;; 
e.printStackTrace&#40;&#41;; 
&#125; 
catch&#40;SQLException e&#41; &#123; 
JOptionPane.showMessageDialog&#40;null,&quot;SQL Exception... Erro na consulta&quot;,&quot;Conexão Falhou&quot;,2&#41;; 
e.printStackTrace&#40;&#41;; 
&#125; 
&#125; 

public void actionPerformed &#40;ActionEvent e&#41; &#123; 

try&#123; 

	if &#40;e.getSource&#40;&#41;==b1&#41; 
		rs.next&#40;&#41;; 
	if &#40;e.getSource&#40;&#41;==b2&#41; 
		rs.previous&#40;&#41;; 
	if &#40;e.getSource&#40;&#41;==b3&#41; 
		rs.first&#40;&#41;; 
	if &#40;e.getSource&#40;&#41;==b4&#41; 
		rs.last&#40;&#41;; 
	if &#40;e.getSource&#40;&#41;==b5&#41; 
		rs.relative&#40;10&#41;; 
	if &#40;e.getSource&#40;&#41;==b6&#41; 
		rs.relative&#40;-10&#41;; 

atualizaCampos&#40;&#41;; 

&#125; 

catch&#40;SQLException erro&#41; &#123; 
JOptionPane.showMessageDialog&#40;null,&quot;Erro no Banco de Dados&quot;,&quot;Erro&quot;,2&#41;; 
erro.printStackTrace&#40;&#41;; 
&#125; 
&#125; 
public void atualizaCampos&#40;&#41;&#123; 

try &#123; 

tfCodigo.setText&#40;rs.getString&#40;&quot;Codigo&quot;&#41;&#41;; 
tfNome.setText&#40;rs.getString&#40;&quot;Nome&quot;&#41;&#41;; 
tfAdmissao.setText&#40;rs.getString&#40;&quot;ADMISSAO&quot;&#41;&#41;; 
tfDemissao.setText&#40;rs.getString&#40;&quot;DEMISSAO&quot;&#41;&#41;; 
tfFuncao.setText&#40;rs.getString&#40;&quot;FUNCAO&quot;&#41;&#41;; 
tfSexo.setText&#40;rs.getString&#40;&quot;SEXO&quot;&#41;&#41;; 

&#125; 

catch&#40;SQLException erro&#41; &#123; 
JOptionPane.showMessageDialog&#40;null,&quot;Erro no Banco de Dados&quot;,&quot;Erro&quot;,2&#41;; 
erro.printStackTrace&#40;&#41;; 
&#125; 
&#125; 
&#125; 

Oi gente!!

Alguma dica sobre minha postagem acima?

Grato,

Edson

Prezado Baleeiro,

Então, conseguiu resolver suas dúvidas?

Atenciosamente,

Edson