一个实验作业,突发奇想改了改。让先去获取数据库表的列数,生成相同列数的表格。
<%@ 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>