日期:2014-05-17  浏览次数:20763 次

怎么通过jsp在网页上把数据库的数据以表格形式显示出来?
我有一段源代码如下:
<%@ page contentType="text/html;charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html";charset=gb2312">
<title>JSP连接数据库</title>
</head>
<body>
<%
String sql=request.getParameter("sqlid");
String mySqlDriver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/mydatabase";
Connection conn;
Class.forName(mySqlDriver).newInstance();
conn = DriverManager.getConnection(url,"root","34497267");
if(conn==null){
System.out.println("get Conn Error");
}
Statement stmt=conn.createStatement();
ResultSet rs=null;
rs=stmt.executeQuery(sql);
while(rs.next())
{
String s1=rs.getString(1);
String s2=rs.getString(2);
String s3=rs.getString(3);
out.println(s1+" | "+s2+" | "+s3+"<br>");
}
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
现在的问题是,我只要改变sqlid传进来的SQL语句(基本针对任何SQL语句),那么这个页面执行的结果能把查到的数据以表格的形式显示出来,不管我的SQL语句是怎么样的,不管数据库中的数据有多少个属性,我只要能最后在页面上正确显示我查的数据的表格显示。我觉的主要是这段的问题:
  while(rs.next())
{
String s1=rs.getString(1);
String s2=rs.getString(2);
String s3=rs.getString(3);
out.println(s1+" | "+s2+" | "+s3+"<br>");
}
不知道怎么改好,哪位大哥有清楚的?告诉我谢谢!

------解决方案--------------------
给个你类似的例子,不知道你是不是这个意思
test.jsp

<%@ page contentType="text/html;charset=utf-8"%>

<html>
<head>
<title>Test page</title>
</head>
<body>
<table border="1">
<%
for (int i = 0; i < 10; i++) {
String s1 = i + "a";
String s2 = i + "b";
String s3 = i + "c";
%>
<tr>
<td><%=s1%></td>
<td><%=s2%></td>
<td><%=s3%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
------解决方案--------------------
<table>
<tr>
<td>编号</td>
<td>用户名</td>
<td>文章名</td>
<td>内容</td>
<td>删除</td>
</tr>
<%
LiuYanming id = new LiuYanImpl();
List<LiuYan> list = id.selectAll();
Iterator it=list.iterator();
while(it.hasNext()){
LiuYan liuyans = (LiuYan)it.next();
%>
<tr>
<td><%=liuyans.getId() %></td>
<td><%=liuyans.getUsername()%></td>
<td><%=liuyans.getLname()%></td>
<td><%=liuyans.getLtextarea()%></td>
<td><a href="delete.do?id=<%=liuyans.getId()%>">删除</a></td>
</tr>
<%}%>
</table>
------解决方案--------------------

就要这样写呀:

<html>
<head>
<title> Test page </title>
</head>
<body>
<table border="1">
<%
while(rs.next())
{
String s1=rs.getString(1);
String s2=rs.getString(2);
String s3=rs.getString(3);
out.pri