Java-Swing:从数据库中检索并更新详细信息

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

Java-Swing: Retrieve and update details in DB

问题

以下是翻译好的部分:

我是一个初学者,正在开发一个Swing桌面应用程序,其中包含一些CRUD(增删改查)功能。虽然我的插入和删除功能正常工作,但更新和检索功能却不正常。

以下是这些服务方法:

  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, String 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.setString(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();
        }  
    }
        

我只是想将一个值检索到文本字段中,并在文本字段中更新该值。

到目前为止,这是我尝试实现的方式:

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
//在这里我已经将id设置为1,供测试使用                                     
            numberOfDays.update(1, jTextField1.getText());
    }   

   private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            

        // 这里我尝试从select方法获取值并设置到文本字段中
        // 但是对于更新,我得到了ArrayIndexOutBounds错误
        // 对于检索,我得到了不允许使用void类型的错误
        jTextField2.setText(numberOfDays.select());
    }   

请注意,你提供的代码片段中可能有些地方存在错误,比如在 select 方法中执行查询后,没有将查询结果用于设置文本字段的值。对于 update 方法,你试图将参数设置到预处理语句中,但实际上不需要设置参数,因为你已经在 SQL 语句中直接嵌入了这些值。此外,select 方法返回类型为 void,因此不能直接用于设置文本字段的值。你可能需要根据你的需求进行一些修正。

英文:

I am a beginner, I am developing a swing desktop application where there are some CRUD functions. While my insertion and deletion are working the update and retrieval is not.

These are the service methods:

  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, String 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.setString(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();
        }  
    }
        

I simply want to retrieve a value to a text field and update the value in a text field.

So far this is how I tried to implement it:

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
//here I have set id as 1 for the sake of testing                                     
            numberOfDays.update(1, jTextField1.getText());
    }   

   private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        jTextField2.setText(numberOfDays.select());
    }   

But for the update, I get ArrayIndexOutBounds error.
For the retrieval, I get void not allowed.

答案1

得分: 2

String sql = "UPDATE working_days_and_hours SET num_of_working_days = ? WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, num);
stmt.setInt(2, id);
stmt.executeUpdate();
stmt.close();

这不是构建PreparedStatement的方式。PreparedStatement的目的是添加一个“?”作为占位符,然后稍后用有效数据替换该占位符。

这样做可以使SQL代码更易编写和阅读,并减少语法错误的机会。

PreparedStatement的格式大致如下:

String sql = "UPDATE Page SET Title = ? WHERE Name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, title);
stmt.setString(2, name);
stmt.executeUpdate();
stmt.close();

其中“title”和“name”是包含你的数据的变量。

所以这不是一个Swing问题。首先使用硬编码的数据使SQL正常工作,然后再考虑从文本字段或其他Swing组件获取数据。

英文:
String sql = "UPDATE working_days_and_hours SET num_of_working_days = '"+num+"' WHERE id = '"+id+"'";

That is not how you build the SQL for a PreparedStatement. The point of the PreparedStatement is add a "?" as a token and then the later replace the token with valid data.

This makes the SQL easier to code and read and will reduce the chance of syntax errors.

The format for a PreparedStatement is something like:

String sql = "UPDATE Page SET Title = ? WHERE Name = ?";

PreparedStatement stmt = connection.prepareStatement(sql);

stmt.setString( 1, title );
stmt.setString( 2, name );
stmt.executeUpdate();
stmt.close();

where "title" and "name" are variables containing your data.

So this is not a Swing issue. First get the SQL working with hardcoded data. Then worry about getting the data from a text field or other Swing component.

huangapple
  • 本文由 发表于 2020年9月11日 04:13:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63837064.html
匿名

发表评论

匿名网友

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

确定