源代码如下
<%@ page import="java.util.*,java.sql.*" pageEncoding="utf-8"%>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<%
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接,exam为数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/exam", "root", "");
//获取statement对象
Statement st = conn.createStatement();
//查询则返回结果集,news为数据表
ResultSet rs = st.executeQuery("select * from news");
%>
<table border="1">
<tr>
<th>序号</th><th>新闻标题</th><th>时间</th>
</tr>
<%
//用while循环来显示商品信息
while(rs.next()){
%>
<tr>
<td><%=rs.getInt(1)%></td><td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
</tr>
<%
}
//最后关闭连接
if(rs!=null) rs.close();
if(st!=null) st.close();
if(conn!=null) conn.close();
%>
</table>
</body>
</html>

数据库中的表如图
本文介绍了如何在Java Server Pages (JSP) 中利用Java Database Connectivity (JDBC) 访问并操作MySQL数据库中的数据。通过示例代码,展示了连接数据库、执行SQL查询和获取结果集的关键步骤。

386

被折叠的 条评论
为什么被折叠?



