在jsp页面直接读取mysql数据库显示数据

闲来无事,学学java,虽说编程语言相通,但是接触一门新知识还是有些疑惑,边学边记录,方便以后温故。

直接给出代码:

 1 <%@page import="java.sql.ResultSet"%>
 2 <%@page import="com.mysql.jdbc.Statement"%>
 3 <%@page import="java.sql.DriverManager"%>
 4 <%@page import="com.mysql.jdbc.Connection"%>
 5 <%@ page language="java" contentType="text/html; charset=gbk"
 6     pageEncoding="gbk"%>
 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 8 <html>
 9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=gbk">
11 <title>Insert title here</title>
12 </head>
13 <body>
14     <%
15         //加载驱动
16         Class.forName("com.mysql.jdbc.Driver");
17         //建立连接
18         Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/house", "root",
19                 "123456");
20         //创建Statement
21         Statement stm = (Statement) conn.createStatement();
22         //执行查询
23         ResultSet rs = stm.executeQuery("select username,pwd from user");
24     %>
25     <table border="1" width="300">
26         <%
27             //遍历结果
28             while (rs.next()) {
29         %>
30         <tr>
31             <td><%=rs.getString(1)%></td>
32             <td><%=rs.getString(2)%></td>
33         </tr>
34         <%
35             }
36         %>
37     </table>
38 </body>
39 </html>

要把mysql驱动包放入项目的WEB-INF/lib下面。刚开始写时候没有对Connection和Statement进行强制转换,老是有红色××,所以要注意注意。

原文地址:https://www.cnblogs.com/luoxiaozhao/p/6952832.html