Java:在Java Swing中实现服务方法。

huangapple go评论72阅读模式
英文:

Java: Implementing service methods in Java Swing

问题

这是我创建的其中一个服务类之一,我已确认它们成功连接到数据库。

public class NumOfDaysService {
    
    // ...(略去未翻译部分)...

    public void addNumberOfDays(WorkingDaysAndHoursModel work) {
        // ...(略去未翻译部分)...
    }
    
    public void select(){
        // ...(略去未翻译部分)...
    }
    
    public void update(int id, int num) {
        // ...(略去未翻译部分)...
    }
        
    public void delete(int id) {
        // ...(略去未翻译部分)...
    }
}

我的问题是,我想要使用这些方法,但我对如何操作有点不太理解。

我如何调用插入方法以响应按钮方法,以及如何调用选择方法以响应文本字段?

英文:

I'm building a desktop app using Java Swing, I've connected the SQLite DB and implemented the service classes already but I'm unable to figure out how to call these methods and implement them in the app.

This is one of the service classes I have created, I have confirmed that they successfully connect to the DB

public class NumOfDaysService {
    
    private static Connection connection;
    private static PreparedStatement preparedStatement;
    private static Statement stmt;
    ResultSet resultSet;
    
    public void addNumberOfDays(WorkingDaysAndHoursModel work) {
        int numberOfDays = work.getNum_of_working_days();
           
        String sql = "INSERT INTO working_days_and_hours(num_of_working_days) VALUES('"+numberOfDays+"')";

      try {
            connection = SQLite_Connection.connect();
            preparedStatement = connection.prepareStatement(sql);
            boolean result = preparedStatement.execute();
            System.out.println("DB status: "+ result);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            //Logger.getLogger(Services.class.getName()).log(Level.SEVERE, null, ex);
        }finally {		
                 // Services.colsedConnections();
        }  
    }
    
     public void select(){
        String sql = "SELECT num_of_working_days FROM working_days_and_hours";
        
         try {
            connection = SQLite_Connection.connect();
            stmt = connection.createStatement();
             resultSet = stmt.executeQuery(sql);
            System.out.println("DB status: "+ resultSet);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            //Logger.getLogger(Services.class.getName()).log(Level.SEVERE, null, ex);
        }finally {		
                 // Services.colsedConnections();
        }  
    }
    
   
     
     public void update(int id, int num) {
        String sql = "UPDATE working_days_and_hours SET num_of_working_days = '"+num+"' WHERE id = '"+id+"'";

        try {
            connection = SQLite_Connection.connect();
            preparedStatement = connection.prepareStatement(sql);
            
            preparedStatement.setInt(1, id);
            preparedStatement.setInt(2, num);

            preparedStatement.executeUpdate();
            
            System.out.println("DB status: "+ preparedStatement);
            
        } catch (Exception ex) {
            System.out.println(ex.toString());
            //Logger.getLogger(Services.class.getName()).log(Level.SEVERE, null, ex);
        }finally {		
                 // Services.colsedConnections();
        }  
    }
        
     public void delete(int id) {
        String sql = "DELETE FROM working_days_and_hours WHERE id = ?";

        try {
            
            connection = SQLite_Connection.connect();
            preparedStatement = connection.prepareStatement(sql);

            // set the corresponding param
            preparedStatement.setInt(1, id);
            // execute the delete statement
            preparedStatement.executeUpdate();
            
        } catch (Exception ex) {
            System.out.println(ex.toString());
            //Logger.getLogger(Services.class.getName()).log(Level.SEVERE, null, ex);
        }finally {		
                 // Services.colsedConnections();
        }  
    }
     
//      public static void main(String[] args) {
//        NumOfDaysService lecturerService = new NumOfDaysService();
//        WorkingDaysAndHoursModel lecturer = new WorkingDaysAndHoursModel(3);
//        Lecturer lecturer2 = new Lecturer(0, "abcd", "123456", "eng", "OC", "Malabe", "new", "level", "rank");

//        lecturerService.addNumberOfDays(lecturer);
//        lecturerService.select();
//        lecturerService.delete(2);
//lecturerService.update(3, 2);

//    }

    
        
}

My question is I want to use these methods but I have little understanding of how to.

How do I call the insert method to a button method and how do I call the select method to a text field?

答案1

得分: 1

你可以通过创建该类的实例,然后调用方法来使用它,例如:

NumOfDaysService service = new NumOfDaysService();
service.addNumberOfDays(work);

然而,该代码存在许多问题,例如:

  • 不要捕获异常并忽略它们。在 Swing 应用程序中,打印可能不会显示在任何地方,因此在该代码中它们真正被忽略了。

  • 由于你在每个方法中连接到数据库,请不要将 Connection 放在静态字段中,而是使用局部变量。

  • 不要将 PreparedStatementStatementResultSet 放在字段中,而应使用局部变量。

  • 通过使用 try-with-resources 来关闭所有的 JDBC 资源。

  • 不要使用字符串拼接来在 SQL 语句中插入值。学习如何使用 PreparedStatement

  • select() 方法在返回数据之前需要使用 ResultSet 获取数据。

  • ...

英文:

You use it by creating an instance of the class, then call the methods, e.g.:

NumOfDaysService service = new NumOfDaysService();
service.addNumberOfDays(work);

However, there are a lot of issues with that code, e.g.:

  • Don't catch exceptions and ignore them. In a Swing application, printing likely goes nowhere, so they are truly ignored in that code.

  • Since you connect to the database in each method, don't put Connection in a static field. Use a local variable.

  • Don't put PreparedStatement, Statement, and ResultSet in fields. Use local variables.

  • Close all the JDBC resources by using try-with-resources.

  • Don't use string concatenation to insert values in a SQL statement. Learn how to use PreparedStatement.

  • The select() method needs to use the ResultSet to get the data before returning.

  • ...

huangapple
  • 本文由 发表于 2020年9月7日 14:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63772332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定