将executeUpdate(sql)或executeQuery(sql)括号中的sql删除。
问题代码:
public static void main(String[] args) throws Exception{
Connection connection = null;
Statement statement = null;
connection = DBHelper.getConnection();
String sql = "update emp set deptno= ? where ename=? ";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,10);
preparedStatement.setString(2,"test");
int i = preparedStatement.executeUpdate(sql); // 增删改
if (i>0){
System.out.println("success");
}else {
System.out.println("failure");
}
DBHelper.close(statement,connection);
}
报错信息:
Exception in thread “main” java.sql.SQLException: ORA-01008: 并非所有变量都已绑定
解决:
首先了解:PrepareStatement接口(面向接口编程),prepareStatement对象会预编译sql语句,这样可以防止多次执行sql语句带来的性能大开销。
我们使用占位符 ? 对sql语句进行简化,但与此同时我们需要调用prepareStatement对象的setXxx()方法去设置占位符所相对应的信息。
String sql = "update emp set deptno= ? where ename=? ";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,10);
preparedStatement.setString(2,"test");
最后,我们通过prepareStatement调用excuteUpdate()或excuteQuery()方法分别进行返回增删改的行数或返回查询的Result结果集。
注意:这里不需要将sql传入excuteUpdate()或excuteQuery()小括号中。这里也是问题所在。
原因:很简单,你直接把String sql = "update emp set deptno= ? where ename=? ";传给增删改查方法,?它无法识别。