====== Java e Postgresql (con Netbeans) ====== Autore: **//Fabio Di Matteo//** \\ Ultima revisione: **//22/12/2017 - 19:11//** \\ \\ Il codice seguente scritto con Netbeans mostra come interagire con Postgresql. Attenzione che il codice sotto il tag ** ** รจ autogenerato da Netbeans.Quello che a noi interessa sono i metodi **main()** e **txtSearchKeyTyped()** **mainFrame.java** /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test0; import javax.swing.UIManager; import javax.swing.table.DefaultTableModel; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; /** * * @author fabio */ public class mainFrame extends javax.swing.JFrame { public DefaultTableModel model ; public static void infoBox(String infoMessage, String titleBar) { JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE); } /** * Creates new form mainFrame */ public mainFrame() { initComponents(); this.setTitle("Esempio swing"); Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://192.168.1.4:5432/test0", "postgres", "postgres"); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM persone;" ); String sql = "Select * from persone"; while ( rs.next() ) { int id = rs.getInt("id"); String nome = rs.getString("nome"); String cognome = rs.getString("cognome"); String email = rs.getString("email"); model = (DefaultTableModel)table1.getModel(); model.addRow(new Object[]{id, nome, cognome, email}); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { e.printStackTrace(); System.out.print("Problemi!\n"); System.err.println(e.getClass().getName()+": "+e.getMessage()); infoBox(e.getClass().getName()+": "+e.getMessage(),"Attenzione"); } } /** * 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") // private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); table1 = new javax.swing.JTable(); txtSearch = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); table1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "id", "Nome", "Cognome", "Email" } )); table1.setName(""); // NOI18N jScrollPane1.setViewportView(table1); txtSearch.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtSearchKeyTyped(evt); } }); 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 687, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(72, Short.MAX_VALUE)) ); pack(); }// private void txtSearchKeyTyped(java.awt.event.KeyEvent evt) { // TODO add your handling code here: Connection c = null; Statement stmt = null; model.getDataVector().removeAllElements(); try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://192.168.1.4:5432/test0", "postgres", "postgres"); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM persone where nome like '%"+txtSearch.getText()+"%';" ); String sql = "Select * from persone"; while ( rs.next() ) { int id = rs.getInt("id"); String nome = rs.getString("nome"); String cognome = rs.getString("cognome"); String email = rs.getString("email"); model.addRow(new Object[]{id, nome, cognome, email}); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { e.printStackTrace(); System.out.print("Problemi!\n"); System.err.println(e.getClass().getName()+": "+e.getMessage()); infoBox(e.getClass().getName()+": "+e.getMessage(),"Attenzione"); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* 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(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable table1; private javax.swing.JTextField txtSearch; // End of variables declaration }