我想创建另一个名为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(){
{
答案 0 :(得分:0)
您应该声明PreparedStatement preparedStmt
和Connection conn
作为您班级的属性。
您可以在构建器中的preparedStmt
和public void save()
中设置conn
。之后,只需从preparedStmt.executeBatch();
拨打public void execute();
,然后关闭conn
。