我正在尝试获取数据库的结果并在线打印但我做错了。我正在使用xampp来托管MySQL中的数据库。我不知道问题是在我的java代码还是在我的HTML中。我尝试了下面的代码,但是当我访问网站并按下返回结果的按钮时,它无法正常工作。所以我无法理解我的问题是与数据库的连接还是HTML代码。这是java代码
public class CloudServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
PrintWriter out;
out=null;
String docType=
"!DOCTYPE HTML PUBLIC\"-//W3C//DTD HTML 4.1"+ "transitional//EN\"\n";
String title="results";
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/mydb";
String query = "Select * FROM TRENDS ORDER BY NUM DESC";
showTable(url,query, out);
resp.getWriter();
}
public void showTable(String url,String query, PrintWriter out){
int num=0;
String Name=null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(rs.getInt(2));
String strI = sb.toString();
Name = rs.getString(1);
out.print(strI+Name);
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
尝试放置ServletOutputStream out = resp.getOutputStream();
而不是PrintWriter
。
答案 1 :(得分:0)
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
PrintWriter out;
out = null;
String docType = "!DOCTYPE HTML PUBLIC\"-//W3C//DTD HTML 4.1" + "transitional//EN\"\n";
String title = "results";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String query = "Select * FROM TRENDS ORDER BY NUM DESC";
// if you do not perform this step,the parameter "out" in the showTable is null
// and may throws NullPointerException
out = resp.getWriter();
showTable(url, query, out);
// I think your problem is in this line
// resp.getWriter();
}