从其他位置运行executebatch()

f0brbegy  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(247)

我想创建另一个名为public void execute()的方法并运行preparedstmt.executebatch();但是我不知道怎么做。

public void save() {
            FacesContext context = FacesContext.getCurrentInstance();

        context.addMessage(null, new FacesMessage("Sacuvano nov proizvod sa sifrom: " + proizvodID + " Naziv proizvoda: " + naziv));
        try {
            String myDriver = "org.gjt.mm.mysql.Driver";
            String myUrl = "jdbc:mysql://localhost/fpis";
            Class.forName(myDriver);
            Connection conn = DriverManager.getConnection(myUrl, "root", "root");

            String query = " insert into proizvod values (?, ?, ?, ?, ?)";

            PreparedStatement preparedStmt = conn.prepareStatement(query);
            preparedStmt.setInt(1, proizvodID);
            preparedStmt.setString(2, naziv);
            preparedStmt.setString(3, opis);
            preparedStmt.setDouble(4, cena);
            preparedStmt.setString(5, jedMere);
            preparedStmt.addBatch();

            preparedStmt.executeBatch();

            conn.close();
        } catch (Exception e) {
            System.err.println("Greska!");
                System.err.println(e.getMessage());
            }

        }
     public void execute(){
        {
qv7cva1a

qv7cva1a1#

你应该申报 PreparedStatement preparedStmt 以及 Connection conn 作为类的属性。就像你可以设置的那样 preparedStmtpublic void save() 以及 conn 在构造函数中。在那之后,就打电话 preparedStmt.executeBatch();public void execute(); 然后关闭 conn 之后。

相关问题