Java jdbc的有关问题

来源:百度知道 编辑:UC知道 时间:2024/05/20 17:52:44
PreparedStatement ps=null;
ResultSet rs=null;
String sql="select * from question order by ?";
try {
ps = this.getConnection().prepareStatement(sql);
ps.setString(1,"price");
rs=ps.executeQuery();
} catch (SQLException ex1) {
}
注:this.getConnection()方法用桥驱动连接数据库:

order by后面的?用prepareStatement处理就异常,运行结果rs=null,如果换下面的处理方法就可以正常运行:
String sql="select * from question order by ";
ps = this.getConnection().prepareStatement(sql+"price");
问题:order by后面要跟的字段名该怎么处理?

PreparedStatement 中的?只能是还没确定的变量值,比如where id=?
而order by 后面是加列名,并不是一个变量的值,所以不能用?表示,只能使用字符串相连将其加到sql语句中

order by 后面加字段名,比如说order by id
要是加上排序的话就在后面加asc或者desc