Connect PostgreSQL JDBC - potatoscript/JavaSwing GitHub Wiki

  1. Download PostgreSQL JDBC driver https://jdbc.postgresql.org/download.html

  2. Move the downloaded jar file to the project folder

    • right click project name -> properties -> Java Build Path -> Libraries -> Add External JARs -> Select the jar file -> Apply and close.
  3. Create constructors

public class JdbcExample extends JFrame{
   public JdbcExample(){
       initUI();
   }
}
  1. Set the JFrame
public static JLabel coords;
private void initUI(){
   
   setTitle("my System Title");
   setSize(300,200);
   
   setLocationRelativeTo(null); //centers the window on the screen
   
   setExtendedState(JFrame.MAXIMIZED_BOTH); //open in full screen
    
   setDefaultCloseOperation(EXIT_ON_CLOSE); // close the window if we click on X button

   ImageIcon webIcon = new ImageIcon("src/resources/myicon.png");
   setIconImage(webIcon.getImage());

   coords = new JLabel("");
   JButton btn = new JButton("BUtton");
   btn.setToolTipText("A button component");
   

   // connection setting
   Connection conn = null;
   String dbURL = "jdbc:postgresql://10.57.10.210:5432/myDB"; // server database url
 
   // Get the dB data and put to table
   Properties param = new Properties();
   param.put("user","myDB");
   param.put("password","myDB");
   
   int n=1;
   try{
      conn = DriverManager.getConnection(dbURL,param);
      if(conn != null){
         String sql = "SELECT * FROM myTable LIMIT 50 ";
         PreparedStatement statement = conn.prepareStatement(sql);
         ResultSet result = statement.executeQuery();
         while(result.next()){
           n++;
         }
        conn.close();
      }
   }catch(SQLException ex){ ex.printStackTrace();}

   Object[][] rawData = new Object[n][3];
   Object[] columnNames = {"A","B","C"};

   try{
      conn = DriverManager.getConnection(dbURL, param);
      if(conn!=null){
        String sql = "SELECT field1, field2, field3 FROM myTable LIMIT 50";
        PreparedStatement statement = conn.prepareStatement(sql);
        ResultSet result = statement.executeQuery();
        while(result.next()){
          int row = result.getRow()-1;
          row.Data[row][0] = result.getString("field1");
          row.Data[row][1] = result.getString("field2");
        }
        conn.close();
      }
   }catch(SQLException ex){ex.printStackTrace();}; 
}