Como dar um Select no banco de dados e mostrar os dados em um jFormattedTextField

3 respostas Resolvido
programaçãojavamysql
N

Olá galera! Eu sou bem iniciante em java e eu estou precisando muito de ajuda neste meu trabalho da faculdade! Eu tenho um programa de “cadastro”, e eu preciso que, quando eu clicar no botão “Consultar” o algoritmo vai ler a chave primaria que eu digitei em um dos jformatted-t-f, vai chamar meu método de consulta na minha classe dao onde está meu comando sql “Select” e vai buscar pelos dados exigidos relacionados a chave primaria digitada pelo usuario anteriormente, após isso, os dados buscados tem que aparecer nos outros jformattedtf correspondentes.

Eu estou travado aqui:

meu método de consulta:

public String nome, nomePai, nomeMae, nomeCurso, rua, setor, cidade, UF, cidadeNascimento, UFNascimento;
 public int CEP;
 public Date dataMatricula,dataNascimento;

 	public void consultar(EAlunos aluno) {
 		
 		String sql=("SELECT nome, nomePai, nomeMae, nomeCurso, dataMatricula, rua, setor, cidade, UF, CEP, dataNascimento, cidadeNascimento, UFNascimento FROM alunos WHERE RA=?");
 		
 		try {
 			
			stmt=con.prepareStatement(sql);
			ResultSet res=stmt.executeQuery();
			//ManterAlunos componentes = new ManterAlunos();
			
			
			while(res.next()) {
				
				nome=String.valueOf(res.getString("nome"));
				//componentes.textFieldNome.setText(nome);
				String nomePai=res.getString("nomePai");
				String nomeMae=res.getString("nomeMae");
				String nomeCurso=res.getString("nomeCurso");
				Date dataMatricula=new Date(res.getDate("dataMatricula").getDate());
				String rua=res.getString("rua");
				String setor=res.getString("setor");
				String cidade=res.getString("cidade");
				String UF=res.getString("UF");
				int CEP=res.getInt("nomePai");
				Date dataNascimento=new Date(res.getDate("dataNascimento").getDate());
				String cidadeNascimento=res.getString("cidadeNascimento");
				String UFNascimento=res.getString("UFNascimento");

				stmt.setString(14, aluno.getRA());
				
//esta parte comentada foi um teste que não deu certo

				/*stmt.setString(1,aluno.setNome(nome));                       
				stmt.setString(2,aluno.setNomePai(nomePai));
				stmt.setString(3,aluno.setNomeMae(nomeMae));
				stmt.setString(4,aluno.setNomeCurso(nomeCurso));
				stmt.setString(5,aluno.setDataMatricula(dataMatricula));
				stmt.setString(6,aluno.setRua(res.getString(rua)));
				stmt.setString(7,aluno.setSetor(setor));
				stmt.setString(8,aluno.setCidade(cidade));
				stmt.setString(9,aluno.setUF(UF));
				stmt.setString(10,aluno.setCEP(CEP));
				stmt.setString(11,aluno.setDataNascimento(dataNascimento));
				stmt.setString(12,aluno.setCidadeNascimento(cidadeNascimento));
				stmt.setString(13,aluno.setUFNascimento(UFNascimento));*/
			}
			
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
 		
 	}

os comandos do botão (só fiz o comando de um jformatted-t-f pra testar):

dao.conectar();
			
			bean.setRA(textFieldRA.getText());
			
			dao.consultar(bean);
			
			textFieldNome.setText(String.valueOf(dao.nome)); <---aqui era pra ele pegar a variavel nome que recebeu o resultSet

E aqui tem o maldito erro:

Conexão bem sucedida.
java.sql.SQLException: No value specified for parameter 1
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
	at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2211)
	at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2191)
	at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2121)
	at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1941)
	at np2.NAlunos.consultar(NAlunos.java:135)
	at np2.ManterAlunos.btnConsultar_actionPerformed(ManterAlunos.java:584)
	at np2.ManterAlunos$5.actionPerformed(ManterAlunos.java:273)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$500(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

Eu preciso urgente disso. Eu agradeço desde já pela atenção.

3 Respostas

G
import java.sql.*;

public class Sql1 {
	
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/public";

   static final String USER = "root";
   static final String PASS = "[telefone removido]";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      
      Class.forName("com.mysql.jdbc.Driver");

      
      System.out.println("Conectado");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      
      System.out.println("Coletando Dados");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT * FROM Java";
      ResultSet rs = stmt.executeQuery(sql);

      while(rs.next()){
         
         int id  = rs.getInt("jav_codigo");
         String c1 = rs.getString("jav_col1");
         String c2 = rs.getString("jav_col2");
         String c3 = rs.getString("jav_col3");

         
         System.out.print(id + " ");
         System.out.print(c1  + " ");
         System.out.print(c2  + " ");
         System.out.println(c3 + " ");
      }
      
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      
      se.printStackTrace();
   }catch(Exception e){
      
      e.printStackTrace();
   }finally{
      
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
}
}

Tente usar esse código que fiz como base para arrumar o seu, esse n tem erro algum e esta 100% funcional.

o jFormatedTextField tente setar o texto em um textfield ou textarea e no seutextfiel.setText(String texto, “Formatação do JFormatedTextField”);

N

Agradeço pela resposta mano, mas eu preciso que esse método de consulta dê os valores do rs para serem impressos nos jftf da janela, e o comando sql tem que buscar pela chave primaria que o usuário digitar em um desses jftf, porém fica dando esses erro:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
	at java.lang.reflect.Constructor.newInstance(Unknown Source)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
	at com.mysql.jdbc.Util.getInstance(Util.java:408)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2441)
	at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1381)
	at np2.NAlunos.consultar(NAlunos.java:137)
	at np2.ManterAlunos.btnConsultar_actionPerformed(ManterAlunos.java:584)
	at np2.ManterAlunos$5.actionPerformed(ManterAlunos.java:273)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$500(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at np2.ManterAlunos.btnConsultar_actionPerformed(ManterAlunos.java:586)
	at np2.ManterAlunos$5.actionPerformed(ManterAlunos.java:273)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$500(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

E eu não entendi o que voce quis dizer com o: jFormatedTextField tente setar o texto em um textfield ou textarea e no seutextfiel.setText(String texto, “Formatação do JFormatedTextField”);

Vlw aí mano.

N
Solucao aceita

Consegui aqui. Um colega da faculdade me ajudou aqui. Vlw pela ajuda!

Criado 6 de novembro de 2017
Ultima resposta 7 de nov. de 2017
Respostas 3
Participantes 2