这是我编写的代码,用于显示从db到浏览器的查询结果,使用servlet
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
// static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
final String DB_URL="jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "postgres";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT docid,term,term_frequency,tf FROM fea2";
ResultSet rs = stmt.executeQuery(sql);
out.println("<h4>connected to db</h4>");
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int docid = rs.getInt("docid");
int term_frequency = rs.getInt("term_frequency");
String term = rs.getString("term");
float tf = rs.getFloat("tf");
//Display values
out.println("ID: " + docid + "<br>");
out.println(", Age: " + term_frequency + "<br>");
out.println(", First: " + term + "<br>");
out.println(", Last: " + tf + "<br>");
}
out.println("</body></html>");
out.println("got data from db");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
此代码仅打印为&#34;数据库结果&#34;在浏览器上,但不是表fea1中的内容。此表存在并填充数据。
的web.xml:
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
我不知道还有什么不对。我想将我的查询结果打印在浏览器上。请帮助。关于我做错了什么的任何建议?
答案 0 :(得分:0)
没有足够的信息来编写一个能够解决您当前编写的问题的答案。
以下是我的建议:
e.printStackTrace()
打印您的堆栈跟踪(打印到System.out),使用e.printStackTrace(out)
找出你在servlet中取得的进展是解决问题的关键。
这可能是其中一个问题:
Class.forName()
失败,因为postgresql驱动程序不在您的类路径上(或者对Servlet的类加载器不可见)DriverManager.getConnection()
可能会失败,因为网址不正确或用户名/密码无效stmt.executeQuery(sql)
可能失败,因为您的SQL语法不正确或对您连接的数据库架构无效。