今天发现JDBC查询mysql时使用prepareStatement像这样写会出问题,但不会报错
String sql = "select ? from emp";
preparedStatement = connention.preparedStatement(sql);
preparedStatement.setString(1,"ename");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
输出结果如下
ename
ename
ename
ename
ename
ename
ename
ename
ename
ename
ename
ename
ename
ename
Process finished with exit code 0
调试了一番,发现SQL代码执行时变成了这样:select 'ename' from emp
select后的列名加上了单引号,变成了字符串,所以无法正确查询;
解决方法:
String sql = "select * from emp";
preparedStatement = conn.prepareStatement(sql);
resultSet = prepareStatement.executeQuery();
while(resultSet.next()){
String ename = resultSet.getString("ename");
double sal = resultSet.getDouble("sal");
System.out.println(ename + "," + sal);
}
本人小白,如有更好的解决方法,还请各位多多指教