(1) 检索
2016-09-25 本文已影响4人
笑笑学生
数据库表:

核心代码:
<%@ page import="java.sql.*"%> //引入相关类库
<body>
<%
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=ShopSystem";
try{
Class.forName(JDriver);
}catch(ClassNotFoundException e){
System.out.println("加载数据库引擎失败");
System.exit(0);
}
try{
String user = "sa";
String password = "xuelong";
Connection con = DriverManager.getConnection(connectDB,user,password);
System.out.println("连接数据库成功");
Statement stmt = con.createStatement();
System.out.println("查询");
System.out.println("开始查询数据");
String strSql="SELECT TOP 5 p_id,p_type,p_name,p_price,p_quantity FROM product order by p_time desc";
ResultSet rs = stmt.executeQuery(strSql);
%>
<center><h2>最新前5位商品信息</h2></center>
<table border="1" align="center">
<tr>
<th>商品编号</th>
<th>商品类别</th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
</tr>
<% while(rs.next()){ %>
<tr bgcolor="blue">
<td><%=rs.getString("p_id") %></td>
<td><%=rs.getString("p_type") %></td>
<td><%=rs.getString("p_name") %></td>
<td><%=rs.getString("p_price") %></td>
<td><%=rs.getString("p_quantity") %></td>
</tr>
<% }%>
</table>
<%
System.out.println("读取完毕");
//当由产生它的Statement关闭或重新执行或用于从多结果序列获得下一个结果时会被自动关闭
//rs.close();
stmt.close();
con.close();
}catch (SQLException e){
out.println(e.toString());
}
%>
</body>