【问题标题】:By clicking on button doesn't make the insertion into data base?通过单击按钮不会插入数据库?
【发布时间】:2016-05-01 00:23:04
【问题描述】:

我在将数据插入到使用 java 创建的 postgres 表中时遇到问题。代码的创建表部分工作正常,只有当我将值插入表时才会发生任何事情。我用来填充表记录的代码是:

 //the first class code
         stmt = c.createStatement();    
     JavaApplication8 dc = new JavaApplication8();
            String sql = "INSERT INTO records (start_date,hour,cell_name,Erlang,ErlangU,cell_type,freq_type) VALUES ( ?,?,?,?,?,?,? )";
        PreparedStatement pst =  c.prepareStatement(sql);
            pst.setInt(1, dc.time());
             pst.setInt(2,heure );
             pst.setString(3, "fgf");
             pst.setFloat(4, 84/10);
             pst.setFloat(5,dc.Hourly_Traffic_900 );
             pst.setInt(6, 1);
             pst.setInt(7, 900);

      stmt.execute(sql);
        stmt.close();
             c.commit();
             c.close();
                  }} catch (ClassNotFoundException | SQLException e) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Records created successfully");}

//the jframe code 
         Connection conn = new DBConnection().Connect();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {

           float bsc = Float.parseFloat(jTextField1.getText());
            float cellsbsc = Float.parseFloat(jTextField2.getText());        
              float days = Float.parseFloat(jTextField3.getText());
         int tot_dense =(int) (bsc*cellsbsc) ;
          JavaApplication8 dc = new JavaApplication8();
           Menu mm = new Menu();
                    Connection c = null;
          Statement stmt = null;

             Class.forName("org.postgresql.Driver");
             c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Records", "postgres", "21262050");
             c.setAutoCommit(false);
             System.out.println("Opened database successfully");

       String sql = "INSERT INTO records (start_date,hour,cell_name,Erlang,ErlangU,cell_type,freq_type) VALUES ( ?,?,?,?,?,?,? )";
             PreparedStatement pst =  c.prepareStatement(sql);
              if (mm.jRadioButton1.isSelected()&& mm.jButton1.isSelected()){

                   for(int i=1; i<tot_dense+1; i++)
                   {
                       for(int d=1; d<days+1; d++)

                       {
                           dc.Day_900();

             pst.setInt(1,dc.time() );
             pst.setInt(2,dc.heure );
             pst.setString(3, "fgf");
             pst.setFloat(4, 84/10);
             pst.setFloat(5,dc.Hourly_Traffic_900);
             pst.setInt(6, 1);
             pst.setInt(7, 900);

             pst.execute();
                       }
                   }

【问题讨论】:

  • 1) 使用逻辑一致的形式缩进代码行和块。缩进是为了让代码流更容易理解! 2) 为了尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • 这一行JavaApplication8 dc = new JavaApplication8();即使在上面的不可编译代码sn-p中也出现了两次。我怀疑这是问题的根源。要以合理的建议交换怀疑,请发布该 MCVE。
  • stmtpst有区别,也可以试试pst.executeUpdate来代替

标签: java swing postgresql user-interface insert-into


【解决方案1】:

所以有几件事情会立即脱颖而出:

  1. 您调用Connection#setAutoCommit 并将其设置为false,但从不调用Connection#commit
  2. 通常,您应该调用PreparedStatement#executeUpdate 而不是execute。它应该不会产生显着差异,但 executeUpdate 实际上会返回受调用影响的行数,这有助于诊断问题。
  3. 您的代码中没有任何迹象表明您实际上正在关闭任何资源
  4. 您在循环中调用 execute,这往往表明可能用于批量更新

因此,您可以做类似...

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

    float bsc = Float.parseFloat(jTextField1.getText());
    float cellsbsc = Float.parseFloat(jTextField2.getText());
    float days = Float.parseFloat(jTextField3.getText());
    int tot_dense = (int) (bsc * cellsbsc);
    JavaApplication8 dc = new JavaApplication8();
    Menu mm = new Menu();

    try {
        Class.forName("org.postgresql.Driver");
        try (Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Records", "postgres", "21262050")) {
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            String sql = "INSERT INTO records (start_date,hour,cell_name,Erlang,ErlangU,cell_type,freq_type) VALUES ( ?,?,?,?,?,?,? )";
            try (PreparedStatement pst = c.prepareStatement(sql)) {
                if (mm.jRadioButton1.isSelected() && mm.jButton1.isSelected()) {

                    for (int i = 1; i < tot_dense + 1; i++) {
                        for (int d = 1; d < days + 1; d++) {
                            dc.Day_900();

                            pst.setInt(1, dc.time());
                            pst.setInt(2, dc.heure);
                            pst.setString(3, "fgf");
                            pst.setFloat(4, 84 / 10);
                            pst.setFloat(5, dc.Hourly_Traffic_900);
                            pst.setInt(6, 1);
                            pst.setInt(7, 900);

                            pst.addBatch();
                        }
                    }
                    pst.executeLargeBatch();
                    //pst.executeBatch();
                    c.commit();
                }

            }
        } catch (SQLException exp) {
            exp.printStackTrace();Ï
        }
    } catch (ClassNotFoundException exp) {
        exp.printStackTrace();
    }
}

查看The try-with-resources Statement 了解更多详情。

说了这么多,接下来跳出来的是……

JavaApplication8 dc = new JavaApplication8();
Menu mm = new Menu();

您正在使用 mm 检查某些单选按钮的状态,因此,除非 Menu 是某种模式对话框,或者单选按钮默认选中状态设置为 true,否则不太可能将永远执行更新代码

但是,它并不止于此,看看第一个代码 sn-p 提出了一些额外的问题......

try {
    stmt = c.createStatement();
    JavaApplication8 dc = new JavaApplication8();
    String sql = "INSERT INTO records (start_date,hour,cell_name,Erlang,ErlangU,cell_type,freq_type) VALUES ( ?,?,?,?,?,?,? )";
    PreparedStatement pst = c.prepareStatement(sql);
    pst.setInt(1, dc.time());
    pst.setInt(2, heure);
    pst.setString(3, "fgf");
    pst.setFloat(4, 84 / 10);
    pst.setFloat(5, dc.Hourly_Traffic_900);
    pst.setInt(6, 1);
    pst.setInt(7, 900);

    stmt.execute(sql);
    stmt.close();
    c.commit();
    c.close();
} catch (ClassNotFoundException | SQLException e) {
    System.err.println(e.getClass().getName() + ": " + e.getMessage());
    System.exit(0);
}

我不知道JavaApplication8 是什么,但我很担心,因为您依赖于该课程的信息。

您同时使用StatementPreparedStatement,但您execute 只使用Statement,这没有意义,因为查询是为PreparedStatement 设置的,所以这只是一团混乱。

如果一切实际成功,您也只会关闭资源,如果查询失败并显示SQLException 会发生什么?这些资源仍然开放!请参阅The try-with-resources Statement 以获得更好的解决方案

因此,代码“可能”看起来更像...

try (Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Records", "postgres", "21262050")) {
    JavaApplication8 dc = new JavaApplication8();
    String sql = "INSERT INTO records (start_date,hour,cell_name,Erlang,ErlangU,cell_type,freq_type) VALUES ( ?,?,?,?,?,?,? )";
    try (PreparedStatement pst = c.prepareStatement(sql)) {
        pst.setInt(1, dc.time());
        pst.setInt(2, heure);
        pst.setString(3, "fgf");
        pst.setFloat(4, 84 / 10);
        pst.setFloat(5, dc.Hourly_Traffic_900);
        pst.setInt(6, 1);
        pst.setInt(7, 900);
        pst.executeUpdate();
    }
} catch (SQLException e) {
    System.err.println(e.getClass().getName() + ": " + e.getMessage());
    System.exit(0);
}
System.out.println("Records created successfully");

例如

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2015-11-30
    • 2015-04-10
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多