alphasil Posted February 22, 2013 at 03:21 PM Report #496644 Posted February 22, 2013 at 03:21 PM Oi ppl Estou a criar uma ligação à uma base de dados mas quando carrego no botão para confirmar login dá-me null o código é este (parte) import java.awt.HeadlessException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ebspma extends javax.swing.JFrame { Connection con=null; ResultSet rs = null; PreparedStatement pst= null; public ebspma() { initComponents(); this.setLocationRelativeTo(null); con = LigacaoBd.conecta(); } // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); us1 = new javax.swing.JTextField(); pw1 = new javax.swing.JPasswordField(); jLabel6 = new javax.swing.JLabel(); escolha1 = new javax.swing.JComboBox(); jSeparator3 = new javax.swing.JSeparator(); jSeparator4 = new javax.swing.JSeparator(); jButton3 = new javax.swing.JButton(); validar = new javax.swing.JButton(); jProgressBar1 = new javax.swing.JProgressBar(); teste = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Requisição Material"); setPreferredSize(new java.awt.Dimension(800, 600)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Entrada", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 12))); // NOI18N jPanel2.setAlignmentX(1.0F); jPanel2.setAlignmentY(1.0F); jPanel2.setPreferredSize(new java.awt.Dimension(350, 260)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel4.setText("Username:"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel5.setText("Password:"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel6.setText("Tipo de User"); escolha1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Escolha", "Administrador", "Docente", " " })); jButton3.setText("Apagar"); validar.setText("Validar"); validar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { validarMouseClicked(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator3) .addComponent(jSeparator4) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 29, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(us1) .addComponent(pw1, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(escolha1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jButton3) .addGap(17, 17, 17) .addComponent(validar))))) .addGap(30, 30, 30)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(us1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(pw1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(escolha1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(validar))) ); jMenu1.setText("File"); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); 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(111, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(110, 110, 110)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(215, 215, 215) .addComponent(teste, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(teste, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold> private void validarMouseClicked(java.awt.event.MouseEvent evt) { if(escolha1.getSelectedItem().equals("Administrador")) { String sql = "select * from admin where user = ? and pass = ?"; try { pst = con.prepareStatement(sql); pst.setString(1,us.getText()); pst.setString(2,pw.getText()); if(escolha1.getSelectedItem().equals("Administrador")); rs = pst.executeQuery(); if(rs.next()) { Admin adm = new Admin(); adm.show(); } else { teste.setText("Erro de login"); } } catch (SQLException | HeadlessException e){ } } } A ligação a BD é este package req; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class LigacaoBd { static Connection conecta() { Connection conexao = null; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/reserva_salas"; String login = "root"; String pass = ""; try { Class.forName(driver); conexao = DriverManager.getConnection(url, login, pass); System.out.println("Ligado à Base de dados"); } catch (ClassNotFoundException | SQLException e) { } return conexao; } } Dá-me erro aqui pst = con.prepareStatement(sql); Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at req.ebspma.validarMouseClicked(ebspma.java:174) Alguma dica?? gmc11
HappyHippyHippo Posted February 22, 2013 at 03:25 PM Report #496646 Posted February 22, 2013 at 03:25 PM que linha +e esta ? : at req.ebspma.validarMouseClicked(ebspma.java:174) IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 06:33 PM Author Report #496670 Posted February 22, 2013 at 06:33 PM Oi HHH Deve faltar código, vou rever. gmc11
alphasil Posted February 22, 2013 at 06:48 PM Author Report #496671 Posted February 22, 2013 at 06:48 PM Aqui esrá revisto inicio package req; import java.awt.HeadlessException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; public class entrada extends javax.swing.JFrame { Connection con = null; ResultSet rs = null; PreparedStatement pst = null; public entrada() { initComponents(); this.setLocationRelativeTo(null); con = LigacaoBd.conecta(); } /** * 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() { jPanel1 = new javax.swing.JPanel(); userLabel = new javax.swing.JLabel(); passLabel = new javax.swing.JLabel(); us = new javax.swing.JTextField(); pw = new javax.swing.JPasswordField(); jComboBox1 = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); delBt = new javax.swing.JButton(); valBt = new javax.swing.JButton(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); openMenuItem = new javax.swing.JMenuItem(); saveMenuItem = new javax.swing.JMenuItem(); saveAsMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); cutMenuItem = new javax.swing.JMenuItem(); copyMenuItem = new javax.swing.JMenuItem(); pasteMenuItem = new javax.swing.JMenuItem(); deleteMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); contentsMenuItem = new javax.swing.JMenuItem(); aboutMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(400, 400)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Formulário de Login")); userLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N userLabel.setText("Username:"); passLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N passLabel.setText("Password:"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Escolha", "Administrador", "Docente" })); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel1.setText("Tipo de User:"); delBt.setText("Apagar"); delBt.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { delBtMouseClicked(evt); } }); valBt.setText("Validar"); valBt.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { valBtMouseClicked(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(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(userLabel) .addComponent(passLabel) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(us) .addComponent(pw) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(delBt) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(valBt))) .addContainerGap(56, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(userLabel) .addComponent(us, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(passLabel) .addComponent(pw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(delBt) .addComponent(valBt)) .addContainerGap()) ); fileMenu.setMnemonic('f'); fileMenu.setText("File"); openMenuItem.setMnemonic('o'); openMenuItem.setText("Open"); fileMenu.add(openMenuItem); saveMenuItem.setMnemonic('s'); saveMenuItem.setText("Save"); fileMenu.add(saveMenuItem); saveAsMenuItem.setMnemonic('a'); saveAsMenuItem.setText("Save As ..."); saveAsMenuItem.setDisplayedMnemonicIndex(5); fileMenu.add(saveAsMenuItem); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); menuBar.add(fileMenu); editMenu.setMnemonic('e'); editMenu.setText("Edit"); cutMenuItem.setMnemonic('t'); cutMenuItem.setText("Cut"); editMenu.add(cutMenuItem); copyMenuItem.setMnemonic('y'); copyMenuItem.setText("Copy"); editMenu.add(copyMenuItem); pasteMenuItem.setMnemonic('p'); pasteMenuItem.setText("Paste"); editMenu.add(pasteMenuItem); deleteMenuItem.setMnemonic('d'); deleteMenuItem.setText("Delete"); editMenu.add(deleteMenuItem); menuBar.add(editMenu); helpMenu.setMnemonic('h'); helpMenu.setText("Help"); contentsMenuItem.setMnemonic('c'); contentsMenuItem.setText("Contents"); helpMenu.add(contentsMenuItem); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setJMenuBar(menuBar); 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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold> private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } private void delBtMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: us.setText(""); pw.setText(""); } private void valBtMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: String sql = "select * from admin where user = ? and pass = ?"; try { pst = con.prepareStatement(sql); pst.setString(1, us.getText()); pst.setString(2, pw.getText()); rs = pst.executeQuery(); if (rs.next()) { JOptionPane.showMessageDialog(null, "Os dados estão corretos "); } else { JOptionPane.showMessageDialog(null, "Os dados estão errados..."); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, e); } } /** * @param args the command line arguments */ 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(entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(entrada.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 entrada().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem contentsMenuItem; private javax.swing.JMenuItem copyMenuItem; private javax.swing.JMenuItem cutMenuItem; private javax.swing.JButton delBt; private javax.swing.JMenuItem deleteMenuItem; private javax.swing.JMenu editMenu; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JMenu fileMenu; private javax.swing.JMenu helpMenu; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JMenuBar menuBar; private javax.swing.JMenuItem openMenuItem; private javax.swing.JLabel passLabel; private javax.swing.JMenuItem pasteMenuItem; private javax.swing.JPasswordField pw; private javax.swing.JMenuItem saveAsMenuItem; private javax.swing.JMenuItem saveMenuItem; private javax.swing.JTextField us; private javax.swing.JLabel userLabel; private javax.swing.JButton valBt; // End of variables declaration } Ligacao BD package req; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class LigacaoBd { static Connection conecta() { Connection conexao = null; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/reserva_salas"; String login = "root"; String pass = ""; try { Class.forName(driver); conexao = DriverManager.getConnection(url, login, pass); System.out.println("Ligado à Base de dados"); } catch (ClassNotFoundException | SQLException e) { } return conexao; } } Quando carregar no "validar" dá isso Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at req.entrada.valBtMouseClicked(entrada.java:235) at req.entrada.access$100(entrada.java:18) at req.entrada$2.mouseClicked(entrada.java:89) at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270) at java.awt.Component.processMouseEvent(Component.java:6508) at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) at java.awt.Component.processEvent(Component.java:6270) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) at java.awt.Container.dispatchEventImpl(Container.java:2273) at java.awt.window.dispatchEventImpl(window.java:2719) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:702) at java.awt.EventQueue$4.run(EventQueue.java:700) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:699) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) gmc11
HappyHippyHippo Posted February 22, 2013 at 06:50 PM Report #496673 Posted February 22, 2013 at 06:50 PM enquanto apresentares código e não responderes às perguntas será impossível te responder que linha é esta ? : at req.entrada.valBtMouseClicked(entrada.java:235) IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 07:04 PM Author Report #496674 Posted February 22, 2013 at 07:04 PM Esta é a linha pst = con.prepareStatement(sql); Vai executar várias instruções na base de dados de forma repetida, neste caso quero que faça uma query para validar dados de login gmc11
HappyHippyHippo Posted February 22, 2013 at 07:06 PM Report #496676 Posted February 22, 2013 at 07:06 PM a variável this.con ainda não foi inicializada no momento da chamada (que pelos vistos é quando carregas no botão do rato sobre alguma coisa) IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 07:19 PM Author Report #496680 Posted February 22, 2013 at 07:19 PM A variável da conexão? mas é iniciada aqui con = LigacaoBd.conecta(); Não estou a ver o que se passa.... gmc11
HappyHippyHippo Posted February 22, 2013 at 07:23 PM Report #496681 Posted February 22, 2013 at 07:23 PM estás a assumir que a ligação foi bem sucedida ... não fazes qualquer tipo de verificação IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 07:32 PM Author Report #496683 Posted February 22, 2013 at 07:32 PM Tenho um exemplo parecido que me funciona....se reparares na LigacaoBd.java tenho um print que me diz que há ligação a BD, neste exemplo a frase não me aparece....que me falta? gmc11
HappyHippyHippo Posted February 22, 2013 at 08:18 PM Report #496686 Posted February 22, 2013 at 08:18 PM o que falta não sei, é impossível responder sem informação ... mas o que deverias fazer era saber que erro deu: try { Class.forName(driver); conexao = DriverManager.getConnection(url, login, pass); System.out.println("Ligado à Base de dados"); } catch (ClassNotFoundException e) { } catch (SQLException e) { System.out.println("Erro de ligação à base de dados : " + e.getMessage()); } IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 08:31 PM Author Report #496688 Posted February 22, 2013 at 08:31 PM Mesmo assim não me aparece a mensagem de erro de ligação a bd.... Estou "lost" gmc11
HappyHippyHippo Posted February 22, 2013 at 08:34 PM Report #496690 Posted February 22, 2013 at 08:34 PM bem ... nesse caso o problema é pior .. .o erro é não teres a classe pedida: try { Class.forName(driver); conexao = DriverManager.getConnection(url, login, pass); System.out.println("Ligado à Base de dados"); } catch (ClassNotFoundException e) { System.out.println("Classe não encontrada : " + e.getMessage()); } catch (SQLException e) { System.out.println("Erro de ligação à base de dados : " + e.getMessage()); } IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 22, 2013 at 10:20 PM Author Report #496707 Posted February 22, 2013 at 10:20 PM Pois bem...nada ainda, vou refazer tudo gmc11
alphasil Posted February 25, 2013 at 04:39 PM Author Report #496951 Posted February 25, 2013 at 04:39 PM De volta Já me faz a ligação à BD mas o código aqui está errado, visto que não me faz nada try { String log = "select * from admin where user = ? and pass = ?"; ResultSet rs = statement.executeQuery(log); PreparedStatement pst = conexaoDB.prepareStatement(log); pst.setString(1, us.getText()); pst.setString(2, pw.getText()); if (rs.next()) { msg.setText("Dados corretos"); } else { msg.setText("Dados incorretos"); } } catch (SQLException | HeadlessException e) { } O código completo está aqui. package gmc; import java.awt.HeadlessException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; public class Entrada extends javax.swing.JFrame { public Statement statement = null; public Connection conexaoDB = null; public Entrada() throws SQLException { initComponents(); this.setLocationRelativeTo(null); DBCon conexao = new DBCon(); conexaoDB = conexao.getConnection(); statement = conexaoDB.createStatement(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); us = new javax.swing.JTextField(); pw = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); combo = new javax.swing.JComboBox(); apagarTexto = new javax.swing.JButton(); validarLogin = new javax.swing.JButton(); msg = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Formulário de Login"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Insira os seus dados", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 12))); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel1.setText("Username:"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel2.setText("Password:"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel3.setText("Tipo de User:"); combo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Escolha", "Administrador", "Docente" })); apagarTexto.setText("Apagar"); apagarTexto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { apagarTextoActionPerformed(evt); } }); validarLogin.setText("Validar"); validarLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { validarLoginActionPerformed(evt); } }); msg.setForeground(new java.awt.Color(255, 0, 0)); msg.setText("jLabel4"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(us) .addComponent(pw, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(apagarTexto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addComponent(validarLogin)) .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(79, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(us, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(msg) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(apagarTexto) .addComponent(validarLogin))) ); 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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold> private void apagarTextoActionPerformed(java.awt.event.ActionEvent evt) { us.setText(""); pw.setText(""); } private void validarLoginActionPerformed(java.awt.event.ActionEvent evt) { if (combo.getSelectedItem().equals("Administrador")) { try { String log = "select * from admin where user = ? and pass = ?"; ResultSet rs = statement.executeQuery(log); PreparedStatement pst = conexaoDB.prepareStatement(log); pst.setString(1, us.getText()); pst.setString(2, pw.getText()); if (rs.next()) { msg.setText("Dados corretos"); } else { msg.setText("Dados incorretos"); } } catch (SQLException | HeadlessException e) { } } } 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(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Entrada.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() { try { new Entrada().setVisible(true); } catch (SQLException ex) { Logger.getLogger(Entrada.class.getName()).log(Level.SEVERE, null, ex); } } }); } // Variables declaration - do not modify private javax.swing.JButton apagarTexto; private javax.swing.JComboBox combo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JLabel msg; private javax.swing.JPasswordField pw; private javax.swing.JTextField us; private javax.swing.JButton validarLogin; // End of variables declaration } Quando faço run aparece-me run: Teste à conexão BD Driver registado A ligação foi efetuada corretamente Algum erro acima? gmc11
HappyHippyHippo Posted February 25, 2013 at 05:15 PM Report #496954 Posted February 25, 2013 at 05:15 PM (edited) o erro é claro, mas se tiveres uma mensagem de erro no catch serás capaz de verificar qual é ps : de preferência que faças output da mensagem da excecção Edited February 25, 2013 at 05:15 PM by HappyHippyHippo IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 25, 2013 at 05:39 PM Author Report #496957 Posted February 25, 2013 at 05:39 PM Pus uma mensagem em catch e diz-me isso You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and pass=?' at line 1 O que não estou a ver visto que noutro exemplo funciona.. Que tem de mal esta linha? "select * from admin where user=? and pass=?" gmc11
HappyHippyHippo Posted February 25, 2013 at 06:17 PM Report #496961 Posted February 25, 2013 at 06:17 PM porque estás a mandar executar uma query e só depois crias o prepared statement, que no final não fazes nada com ele ? IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted February 25, 2013 at 06:37 PM Author Report #496965 Posted February 25, 2013 at 06:37 PM (edited) Tens razão, estava a executar a query antes, mas mesmo assim há algo de errado, tenho o mesmo erro private void validarLoginActionPerformed(java.awt.event.ActionEvent evt) { if (combo.getSelectedItem().equals("Administrador")) { try { String log = "select * from admin where user=? and pass=?"; PreparedStatement pst = conexaoDB.prepareStatement(log); pst.setString(1, us.getText()); pst.setString(2, pw.getText()); ResultSet rs = statement.executeQuery(log); if (rs.next()) { msg.setText("Dados corretos"); } else { msg.setText("Dados incorretos"); } } catch (SQLException | HeadlessException e) { System.out.println("Erro : " + e.getMessage()); } } } Teste à conexão BD Driver registado A ligação foi efetuada corretamente Erro de ligação à base de dados : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and pass=?' at line 1 BUILD SUCCESSFUL (total time: 11 seconds) Já não percebo o que se passa Edited February 25, 2013 at 06:37 PM by alphasil gmc11
HappyHippyHippo Posted February 25, 2013 at 07:12 PM Report #496973 Posted February 25, 2013 at 07:12 PM crias o prepared statement mas não fazes nada com ele ... pensa no que realmente estás a fazer na seguinte linha : ResultSet rs = statement.executeQuery(log); // aonde nesta linha aparece o "pst" ?? IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now