1 回答

TA貢獻(xiàn)1798條經(jīng)驗 獲得超7個贊
引用javadoc?executeUpdate()
:
返回:
(1)?SQL 數(shù)據(jù)操作語言 (DML) 語句的行計數(shù)或 (2) 0(不返回任何內(nèi)容的 SQL 語句)
所以:
String url = "jdbc:derby://localhost:1527/Cookbook";
try (Connection conn = DriverManager.getConnection(url)) {
? ? String query = "DELETE from RECIPES WHERE NAME = ?";
? ? try (PreparedStatement pst = conn.prepareStatement(query)) {
? ? ? ? pst.setString(1, name);
? ? ? ? int rowCount = pst.executeUpdate();
? ? ? ? if (rowCount == 0) {
? ? ? ? ? ? JOptionPane.showMessageDialog(null, "'" + name + "' was not found");
? ? ? ? } else if (rowCount == 1) {
? ? ? ? ? ? JOptionPane.showMessageDialog(null, "'" + name + "' was successfully deleted");
? ? ? ? } else { // cannot happen if `NAME` has unique index in the database
? ? ? ? ? ? JOptionPane.showMessageDialog(null, rowCount + " recipes named '" + name + "' were deleted");
? ? ? ? }
? ? }
} catch (Exception e) {
? ? JOptionPane.showMessageDialog(null, "something went wrong: " + e);
}
添加回答
舉報