繁体   English   中英

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

[英]Java-Swing: Retrieve and update details in DB

我是初学者,我正在开发一个带有一些 CRUD 功能的 Swing 桌面应用程序。 虽然我的插入和删除工作正常,但更新和检索却没有。

这些是服务方法:

  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) {   
//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());
    }   

但是对于更新,我收到 ArrayIndexOutBounds 错误。 对于检索,我不允许无效。

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

这不是您为PreparedStatement构建 SQL 的方式。 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 组件获取数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM