Search code examples
javasqljdbcjbuttonjtextarea

Refresh Query upon botton selected JAVA


I have this jdbc code that fills my JtextArea with query data based on my "String Fecha" what i need is a button that can change the Fecha string value and make the query Re-Execute so the JtextArea gets new values based on the new query made by the new value of String Fecha, but i have no idea how to do this can some1 tell me with a example?

This is my Query Code:

try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn3 =     DriverManager.getConnection("jdbc:sqlserver://ARTURO-LAPTOP;user=sa;password=sacompusis;database=PDV");
        st3 = conn3.createStatement();
        rs3= st3.executeQuery("SELECT Nombre_Pdv, SUM(Total) AS Expr1 FROM   VENTA_PLATILLOS where Fecha ='"+fecha+"' GROUP BY Nombre_Pdv");

        StringBuilder sb = new StringBuilder();
       /* sb.append("Ingresos por Punto de Venta" + "\n" +"");*/
        while(rs3.next()){
            sb.append(rs3.getString(1) +"\n"+ rs3.getString(2)+"\n");
        }
        textArea.setFont(new Font("Monospaced", Font.BOLD, 15));
        textArea.setEditable(false);
        textArea.setText(sb.toString());

    }
    catch(Exception e){
        e.printStackTrace();
    }

I need a butto that changes the "String fecha" value on click and make the query excecutes again


Solution

  • For the GUI part of your request, any basic tutorial will give you the answer.

    For the JDBC code, I would recommend a code following the next remarks:

    • the user you provide for the connection to your database is defined in the URL. It is a bad idea for obvious security reason (access to your code gives you access to the database). Put that info in a secure place where it can easily be changed (for security reason as well), recover them at runtime, and use rather the next syntax:

      Connection dBConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
      
    • do not connect to the database each time you have a request to send. It is not performant. The time for establishing the connection can take several hundreds of milliseconds. Establish the connection at the start of your application and keep it in memory and recover it each time you have a request to send. Do not forget to close it when you close your application!

    • you've got a parameter in your select SQL command so it is better to use a JDBC PreparedStatement rather than a simple Statement. Advantage: it will be compiled once and only once (it is keeped in the JDBC connection cache). In your case, there is a GUI in the loop so it is not a huge advantage. But in an online Internet application with many users, the improvement of performance is more than significant. So it is better to learn this good practice.

      private static final String GET_MY_INFO = "SELECT nombre_pdv, SUM(total) " +
                                                "FROM venta_platillos " +
                                                "WHERE fecha = ? " +
                                                "GROUP BY nombre_pdv";
      ...
      StringBuilder sb = new StringBuilder();
      try (
          PreparedStatement stmt = dBConnection.prepareStatement(GET_MY_INFO);
      ) {
          stmt.setX(1, fetcha);
          ...
          try (
              ResultSet rset = stmt.executeQuery();
          ) {
              while (rset.next()) {
                  sb.append(rset.getString(1) +"\n"+ rset.getString(2)+"\n");
              }
          }
      }
      // use sb as you want
      ...
      

      here X in setX() must be replaced by the type of variable fetcha.

    • It is better to put your Statement or PreparedStatement and ResultSet in try-with-resource block (block with try followed by parenthesis / brackets). Like that they will be automatically closed at the exit of the block even in case of exception. It is important to close them because it releases all JDBC resources used. And with try-with-resource block you do not have to manage it manually (generally badly done specially in case of exception).