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.youkuaiyun.com/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); } } }