JSP 用表格显示数据库信息(自适应表格)

一个实验作业,突发奇想改了改。让先去获取数据库表的列数,生成相同列数的表格。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.sql.*" %>
    
<!DOCTYPE html>
<html>

<style>
table{
    border-collapse: collapse;
    
}
</style>

<head>
<meta charset="UTF-8">
<title></title>
</head>
<body bgcolor="#abeded">

<%
Connection con=null;
String sql=null;
Statement stmt=null;

try {
	Class.forName("com.mysql.jdbc.Driver");//加载JDBC-MySQL驱动
} catch (Exception e) {
	out.println("加载驱动器类时出现异常");
}

String DBName = "ch08";
String uri="jdbc:mysql://localhost:3306/"+
		DBName+"?useSSL=true&characterEncoding=utf-8";

String user = "root";
String password = "";

try {
	con = DriverManager.getConnection(uri,user,password);//连接数据库代码
} catch (SQLException e) {
	out.println("连接数据库的过程中出现SQL异常");
}

try {
	//创建Statement语句
	stmt = con.createStatement();
	//先查询有多少列
	sql="desc student;";
	
	//使用executeQuery执行SQL查询语句
	ResultSet rs=stmt.executeQuery(sql);
	%>
	
	<table border="1" align="center">
		<tr>
			<% 
			//获取列属性名
			//i=列数
			int i=0;
			while(rs.next()){
				%>
				<td align="center"><%=rs.getString(1) %></td>
				<%
				i++;
			}
			%>
			
		</tr>
		
		<% 
		sql="select * from student where 编号 BETWEEN 11 AND 13;";
		rs=stmt.executeQuery(sql);
		//显示获取的结果集
		while(rs.next()){
			%>
			<tr>
				<% 
				for(int j=1;j<=i;j++){
					%>
					<td align="center"><%=rs.getString(j) %></td>
					<%
				}
				%>
			</tr>
			<%
		}
		%>
		
	</table>
	
	<%
	
} catch (SQLException e) {
	out.println("出现SQL异常");
}

try{
	if(con!=null)
		con.close();
}catch(SQLException e){
	out.println("关闭数据库连接时出现SQL异常");
}

%>

</body>
</html>
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值