想要对数据库进行修改数据的操作,可以通过 Statement 的 executeUpdate()方法,如果在
executeUpdate()方法中的sql语句为update语句,即可修改数据库中指定的数据。
下面在BookDAO类中增加一个修改Book表中指定记录的方法:
//修改咖啡表中某个咖啡的信息
public void update(BookBean Book) {
String updateStr = "update book set sup_id=" + book.getSupplierId()
+ ",price=" + book.getPrice()
+ ",type=" + book.getType()
+ " where bok_name='" + book.getBookName() + "'";
try (Connection con = JDBCUtilities.getConnection();
Statement stmt = con.createStatement()) {
int result = stmt.executeUpdate(updateStr);
if (result > 0) {
System.out.println("更新成功");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
编写一个测试程序,测试上面的方法。测试的部分代码如下:
BookDAO bookDAO = new BookDAO();
System.out.println("修改记录前:");
bookDAO.viewTable();
BookBean newBook = new BookBean("China Tea2",101,98.90f,0,0); //代表要修改的新的信息
bookDAO.update(newCoffee);
System.out.println("修改记录后:");
bookDAO.viewTable();
executeUpdate()方法中的sql语句为update语句,即可修改数据库中指定的数据。
下面在BookDAO类中增加一个修改Book表中指定记录的方法:
//修改咖啡表中某个咖啡的信息
public void update(BookBean Book) {
String updateStr = "update book set sup_id=" + book.getSupplierId()
+ ",price=" + book.getPrice()
+ ",type=" + book.getType()
+ " where bok_name='" + book.getBookName() + "'";
try (Connection con = JDBCUtilities.getConnection();
Statement stmt = con.createStatement()) {
int result = stmt.executeUpdate(updateStr);
if (result > 0) {
System.out.println("更新成功");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
编写一个测试程序,测试上面的方法。测试的部分代码如下:
BookDAO bookDAO = new BookDAO();
System.out.println("修改记录前:");
bookDAO.viewTable();
BookBean newBook = new BookBean("China Tea2",101,98.90f,0,0); //代表要修改的新的信息
bookDAO.update(newCoffee);
System.out.println("修改记录后:");
bookDAO.viewTable();