使用JSP原生开发查询数据,用PreparedStatement将数据包装成List Map显示在页面(不用任何第三方jar包)
<%@ page import="java.sql.*" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %><%--
Created by IntelliJ IDEA.
User: HBCK_PC
Date: 2020/7/16
Time: 15:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String url = "your host";
String user = "your username";
String password = "your password";
Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = conn.prepareStatement("select * from tbl_lanmu");
ResultSet resultSet = preparedStatement.executeQuery();
List<Map<String,Object>> dataList = new ArrayList<>();
while (resultSet.next()) {
ResultSetMetaData metaData = resultSet.getMetaData();
Map<String,Object> dataMap = new HashMap<>();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String key = metaData.getColumnName(i + 1);
Object value = resultSet.getObject(i + 1);
dataMap.put(key,value);
}
dataList.add(dataMap);
}
if (dataList.size() > 0) {
out.println("<span style='color:red;'>数据总数:"+dataList.size()+"条</span>");
out.println("</hr>");
out.println("<table border='1' cellspacing='0' cellpadding='0'>");
Map<String, Object> firstData = dataList.get(0);
out.println("<tr>");
for (Map.Entry<String, Object> entry : firstData.entrySet()) {
out.println("<td>");
out.println(entry.getKey());
out.println("</td>");
}
out.println("</tr>");
for (Map<String, Object> object : dataList) {
out.println("<tr>");
for (Map.Entry<String, Object> entry : object.entrySet()) {
out.println("<td>");
out.println(entry.getValue());
out.println("</td>");
}
out.println("</tr>");
}
out.println("</table>");
}
%>
</body>
</html>