为什么我只从mysql数据库中得到最后一个结果,无论db中有哪些元素都没关系?如何检索我的所有数据库行?
这是代码:
package database;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
public class getData extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con;
Statement stmt;
ResultSet rs;
Setzen setze = new Setzen();
int zeilen;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ausgaben","***","***");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM ausgaben");
ResultSetMetaData meta = rs.getMetaData();
zeilen = meta.getColumnCount();
while(rs.next())
{
setze.setAusgaben(rs.getString("Ausgaben"));
setze.setVom(rs.getString("vom"));
setze.setPreis(rs.getString("Preis"));
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(setze.getAusgaben());
PrintWriter out = response.getWriter();
String data = "{\"sEcho\":" + 3 + ",\"iTotalRecords\":" + zeilen + ", \"iTotalDisplayRecords\":" + zeilen + ",\"aaData\":[["+"\""+setze.getAusgaben()+"\""+","+"\""+setze.getVom()+"\""+","+"\""+setze.getPreis()+"\""+"]]}";
System.out.println(data);
out.print(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
提前谢谢你。
答案 0 :(得分:1)
看起来问题在于Setzen
类的实现。我确定setXXX()
方法不会附加数据,而是会覆盖最后写入的数据。
此外,如果在Java 7上,请考虑使用try-with-resources
,但这与您的问题无关。
答案 1 :(得分:0)
您将所有结果保存到一个对象setze
。
看起来你想要收集所有结果并将它们作为某种JSON结构返回。您应该使用json.org Java package尝试这样的事情。它避免了手动创建JSON输出时可能出现的巨大错误来源。
final JSONArray ja = new JSONArray();
while (rs.next()) {
ja.put(new JSONObject()
.put("Ausgaben", rs.getString("Ausgaben"))
.put("vom", rs.getString("vom"))
.put("Preis", rs.getString("Preis")));
}
response.getWriter().print(new JSONObject()
.put("aaData", ja)
.put("iTotalRecords", zeilen)
.toString());
这将输出类似{"iTotalRecords":3,"aaData:[{"Ausgaben":"...","vom":"...","Preis":"..."},...]}
我还建议在发生异常时向用户发送错误,而不是默默地忽略它。
catch (SQLException e) {
// TODO: log the exception
// this is our fault, let the user know we failed
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}