1、Parameter index out of range (1 > number of parameters, which is 0).報錯
查看一下SQL語句是不是將英文輸入法的 佔位符 "?" 寫成 中文輸入法的 “?”。
2、Before start of result set 報錯
try{
......
// 5.執行SQL語句並返回 ResultSet 結果
ResultSet rs = psmt.executeQuery();
// 6.遍歷ResultSet結果集
while (rs.next()) {
......
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 7.釋放資源
}
查看一下遍歷結果集時,while()中有沒有使用 next() 方法,小編就馬虎的寫成了 rs!=null,修改過來後使用 rs.next() 就沒問題了 。
3、unreachable statement 報錯
遙不可及的聲明,即不可達的語句。小編是在 throw 語句後邊添加了語句,然後百度了一下,下邊這條鏈接寫的挺好的。
參考 https://blog.csdn.net/qq_33915826/article/details/79246482
4、Cannot delete or update a parent row: a foreign key constraint fails (`shop`.`orderitem`, CONSTRAINT `orderitem_ibfk_2` FOREIGN KEY (`pno`) REFERENCES `product` (`pid`))
刪除數據庫記錄時報錯,原因是刪除的記錄與其他表中存在外鍵關係,需要將所有與此條記錄有關的外鍵全部刪除後,再刪除該條記錄,並刪除與此條記錄所關聯的所有記錄後,然後再將外鍵添加回來。這樣纔是成功的刪除了一條記錄。
// 根據id刪除商品信息(商品表關聯了商品分類表,需先刪除外鍵再刪除商品信息,然後再添加外鍵) @Test public void testDeleteById() { PreparedStatement pdfc = null; PreparedStatement pdfoi = null; PreparedStatement pdri = null; PreparedStatement pafc = null; PreparedStatement pafoi = null; try { conn.setAutoCommit(false);//開啓事務(關閉自動提交) // 預編譯並刪除與商品分類表關聯的外鍵 String deleteForeignCategory = "ALTER TABLE product DROP FOREIGN KEY product_fk"; pdfc = conn.prepareStatement(deleteForeignCategory); pdfc.executeUpdate(); // 預編譯並刪除與訂單表關聯的外鍵 String deleteForeignOrderItem = "ALTER TABLE orderitem DROP FOREIGN KEY orderitem_fk_2"; pdfoi = conn.prepareStatement(deleteForeignOrderItem); pdfoi.executeUpdate(); // 預編譯並刪除商品信息 String deleteProductSql = "DELETE FROM `product` WHERE pid=?"; psmt = conn.prepareStatement(deleteProductSql); psmt.setInt(1, 8); int i = psmt.executeUpdate(); // 因爲訂單表中有與商品信息關聯的數據,因此也要刪除訂單表中的數據 // 預編譯並刪除訂單表信息 String deleteOriderItemSql = "delete from orderitem where pno=?"; pdri = conn.prepareStatement(deleteOriderItemSql); pdri.setInt(1, 8); pdri.executeUpdate(); // 預編譯並添加與商品分類表有關的外鍵 String addForeignCategory = "ALTER TABLE product ADD CONSTRAINT`product_fk` FOREIGN KEY(cno) REFERENCES category(cid)"; pafc = conn.prepareStatement(addForeignCategory); pafc.executeUpdate(); // 預編譯並添加與訂單表有關的外鍵 String addForeignOrderItem = "ALTER TABLE orderitem ADD CONSTRAINT`orderitem_fk_2` FOREIGN KEY(pno) REFERENCES product(pid)"; pafoi = conn.prepareStatement(addForeignOrderItem); pafoi.executeUpdate(); // 判斷是否成功刪除數據 if (i > 0) { System.out.println("刪除商品成功"); } else { System.out.println("刪除商品失敗"); } // 提交事務 conn.commit(); } catch (SQLException e) { try { // 如果存在異常,回滾事務 conn.rollback(); System.out.println("發生異常,回滾事務"); } catch (SQLException ex) { throw new RuntimeException(ex); } throw new RuntimeException(e); } finally { //7.釋放資源 try { if (rs != null) { pafoi.close(); } if (rs != null) { pafc.close(); } if (rs != null) { psmt.close(); } if (rs != null) { pdri.close(); } if (rs != null) { pdfoi.close(); } if (rs != null) { pdfc.close(); } if (rs != null) { conn.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } }