使用PreparedStatement删除Oracle数据时遭遇ORA-01008错误求助
解决ORA-01008: not all variables bound异常
问题原因
你代码中的核心错误是调用了statement.executeUpdate(sql)。当使用PreparedStatement时,传入SQL字符串的executeUpdate(String)方法属于父类Statement的范畴——它会重新执行原始的带占位符的SQL,完全忽略你之前通过setInt(1,101)绑定的参数,导致Oracle检测到未赋值的占位符,抛出"not all variables bound"异常。
修复方案
将带参数的executeUpdate(sql)替换为PreparedStatement的无参executeUpdate()方法,这样会使用你已经绑定好参数的预编译SQL执行删除操作。
修正后的完整代码
Class.forName("oracle.jdbc.driver.OracleDriver"); dbURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 修正URL拼写错误(jbdc→jdbc) username = "system"; password = "tiger"; connection = DriverManager.getConnection(dbURL, username, password); System.out.println("Connected Successfully Database "); String sql = "delete from employee where emp_id=? "; statement = connection.prepareStatement(sql); statement.setInt(1, 101); int result = statement.executeUpdate(); // 去掉传入的sql参数 System.out.println(result + " record deleted"); connection.close(); System.out.println("Connection Successfully Closed");
额外注意事项
- 务必修正URL拼写:原代码中的
jbdc是错误写法,正确应为jdbc,虽然这不是当前异常的触发原因,但会导致数据库连接失败。 - 使用
PreparedStatement时,所有执行方法(execute()、executeUpdate()、executeQuery())都不能传入SQL字符串,否则会失去预编译和参数绑定的优势,同时引发类似的参数绑定异常。
内容的提问来源于stack exchange,提问作者SHUBHAM SHEDGE
相关产品推荐
相关产品推荐

