[英]using ORDER BY in a prepared statement
I'm creating a web app that displays a table using data from a database using Java MVC. 我正在创建一个Web应用程序,该应用程序使用Java MVC使用数据库中的数据显示表。
I have a prepared statement that I'm using to generate the table that works fine until i try and use ORDER BY. 我有一个准备好的语句,可以用来生成在我尝试使用ORDER BY之前可以正常工作的表。
I'm quite confused as when I run this query in the mySQL workbench it works fine: 我很困惑,因为我在mySQL工作台中运行此查询时工作正常:
SELECT * FROM appointments ORDER BY date
However when i put it into my prepared statement in the browser it returns an unordered list. 但是,当我将其放入浏览器中的准备好的语句中时,它将返回无序列表。
public void doRead(){
String query = "SELECT * FROM appointments ORDER BY date";
try {
PreparedStatement ps = this.connection.prepareStatement(query);
this.results = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Would appreciate any help. 将不胜感激。
as requested im printing the table with this method here: 根据要求,我在这里使用此方法打印表格:
try {
while(this.results.next()){
Appointment appointment = new Appointment();
appointment.setAppointmentID(this.results.getInt("appointment_id"));
appointment.setDescription(this.results.getString("description"));
appointment.setDate(this.results.getString("date"));
table += "<tr>";
table += "<td>";
table += appointment.getDescription();
table += "</td>";
table += "<td>";
table += appointment.getDate();
table += "</td>";
table += "</tr>";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
table += "</table>";
return table;
}
the output in browser: 浏览器中的输出:
Dentist 2015-09-17 牙医2015-09-17
Dentist 2015-09-17 牙医2015-09-17
Dentist 2015-09-17 牙医2015-09-17
Dentist 2015-10-09 牙医2015-10-09
Dentist 2015-09-03 牙医2015-09-03
Dentist 2015-09-03 牙医2015-09-03
Dentist 2015-09-03 牙医2015-09-03
DATE is a reserved word . DATE是保留字 。 Use backticks: 使用反引号:
String query = "SELECT * FROM appointments ORDER BY `date`";
Also better make results
a local variable and close it. 还可以更好地使results
成为局部变量并将其关闭。
Tip: 小费:
Use a StringBuilder instead of String for table
. table
使用StringBuilder而不是String。 Much faster, less memory hungry. 更快,更少的内存消耗。 Better even would be to pass a PrintWriter for outputting. 甚至最好是传递一个PrintWriter进行输出。
尝试添加排序顺序“ ASC”:
SELECT * FROM appointments ORDER BY date ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.