gpt4 book ai didi

java - 将 SQL 选择结果集直接打印到 HTML 网页上?

转载 作者:行者123 更新时间:2023-11-29 06:52:24 26 4
gpt4 key购买 nike

如何重写下面的代码以直接在网页上而不是在控制台上打印结果?

 public static void doSQL() {
try {
String url = "jdbc:msql://...";
Connection conn = DriverManager.getConnection(url,"user","password");
Statement stmt = conn.createStatement();
ResultSet rs;

rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {

// I want to print the ResultSet directly on my HTML page, how may I go about doing that?
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {

System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}

最佳答案

一种方法是从 servlet 响应中获取 writer,然后编写您想要的 HTML 内容。我对您的 doSQL() 方法进行了轻微重构,以接受 PrintWriter 作为参数。

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
doSQL(pw);
}

public static void doSQL(PrintWriter pw) {
try {
String url = "jdbc:msql://...";
Connection conn = DriverManager.getConnection(url,"user","password");
Statement stmt = conn.createStatement();
ResultSet rs;

rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
pw.println("<html><table>");
while (rs.next()) {
// you only select one field, but you can easily adapt
// this code to have more fields (i.e. table columns)
String lastName = rs.getString("Lname");
pw.println("<tr><td>" + lastname + "</td></tr>");
}
pw.println("</table></html>");
conn.close();
} catch (Exception e) {

System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

关于java - 将 SQL 选择结果集直接打印到 HTML 网页上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com