我遇到的问题是我要创建一个 servlet,它将从三个表 (SQL) 中获取数据并将它们打印在 html 表中。
表的结构如下:
博客评论:
row id (auto increments),
blogger id,
entry_tstamp,
t_stamp,
comment,
author_id,
博客条目:
row id(auto increments),
blogger_id,
timestamp,
entry,
博主信息:
row id(auto increments),
blogger_id,
name,
email address,
image,
password,
博客条目是原始帖子,而 blog_comments 与该帖子相关。我正在尝试创建一个表,该表将显示博主详细信息,然后在第一行和第二行及以下显示帖子(来自 blog_entries),以及对该博客的相关评论。
我正在尝试使用 while 语句(如下所示)。我必须使用 while 语句来最初获取初始博客文章和博主 ID,然后使用第二个 while 语句来显示与此相关的评论。
我在通过第二个while循环时遇到了一些困难,它取消了第一个while循环(在一个增量之后),然后转储了第二个while循环的内容。
有谁知道是否有更好的方法来实现这一点?我应该使用比较循环吗?而且我确定我的编码是错误的。谁能告诉我哪里出错了?
谢谢你。
代码:
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:E:/My Documents/NetBeansProjects/co2509blog.sqlite");
stmt = con.createStatement();
//String temp = "SELECT entry, name, email, image, comment from blog_comments C, blog_entries E, blogger_info I where E.blogger_id = I.blogger_id AND I.blogger_id = C.author_id ORDER BY E.timestamp";
//String temp = "SELECT entry, name, email, image from blog_entries E, blogger_info I where E.blogger_id = I.blogger_id ORDER BY E.timestamp";
//String temp = "SELECT entry, name, email, image, comment from blogger_info I JOIN blog_entries E ON I.blogger_id = E.blogger_id JOIN blog_comments C ON I.blogger_id = C.author_id WHERE E.timestamp = C.entry_tstamp ORDER BY E.timestamp";
String query = "SELECT name, image, email, entry FROM blogger_info I, blog_entries E WHERE I.blogger_id = E.blogger_id ORDER BY E.timestamp";
String query2 = "SELECT name, image, email, comment FROM blogger_info I, blog_entries E, blog_comments C WHERE I.blogger_id = C.author_id AND E.timestamp = C.entry_tstamp ORDER BY E.timestamp";
rs = stmt.executeQuery(query);
//rs2 = stmt.executeQuery(secondQuery);
// displaying records
int rowCount = 0;
int rowCount2 = 0;
out.println("<P ALIGN='center'><TABLE BORDER=5>");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columnCount = rsmetadata.getColumnCount();
// table header
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TH>" + rsmetadata.getColumnLabel(i + 1) + "</TH>");
}
out.println("</TR>");
{
while (rs.next()) {
rowCount++;
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TD>" + rs.getString(i + 1) + "</TD>");
}
rowCount2++;
rs2 = stmt.executeQuery(query2);
ResultSetMetaData rsmetadata2 = rs2.getMetaData();
int columnCount2 = rsmetadata2.getColumnCount();
rsmetadata2 = rs2.getMetaData();
out.println("</TR>");
while (rs2.next()) {
rowCount2++;
out.println("<TR>");
for (int j = 0; j < columnCount2; j++) {
out.println("<TD>" + rs2.getString(j + 1) + "</TD>");
}
}
}
out.println("</TR>");
}
out.println("</TABLE></P>");
}