📄 random.jsp
字号:
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<HTML>
<head>
<title>Random Selection</title>
</head>
<BODY>
<%
//驱动程序名、数据库用户名、密码、数据库名、表名
String driverName="com.mysql.jdbc.Driver";
String username="root";
String password="yesterdayn";
String dbName="study";
String tableName="product";
//联结字符串
String url="jdbc:mysql://localhost/"+dbName+"?characterEncoding=GBK";
try{
//加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//建立同数据库的连接对象
Connection connection=DriverManager.getConnection(url,username,password);
Statement statement = connection.createStatement();
String sql="SELECT * FROM "+tableName;
//发送执行SQL语句
ResultSet rs = statement.executeQuery(sql);
//获取结果集中的总记录行数
rs.last();
double total=rs.getRow();
//获取一个小于最大行的随机行号
double u=(Math.random())*total;
if(u<=0.5) //以防出现小于0.5的值而出错
u=1;
int p=(int)Math.round(u);
out.print("数据库连接成功!随机数为:"+u+" 指针位置:"+p+"<BR>");
out.print("<TABLE BORDER=1 bordercolorlight=#000000 >");
out.print("<TR><TD width=40>序号</TD>");
out.print("<TD width=60>代码</TD><TD width=80>商品名称</TD>");
out.print("<TD width=60>品牌</TD>");
out.print("<TD width=150>产品简介</TD><TD width=80>存货数量</TD>");
out.print("<TD width=80>价格/元</TD></TR>");
rs.absolute(p); //将记录指针指向第p行
out.print("<TR>");
out.print("<TD>"+rs.getInt(1)+"</TD>");
out.print("<TD>"+rs.getString("pdm")+"</TD>");
out.print("<TD>"+rs.getString("pname")+"</TD>");
out.print("<TD>"+rs.getString("provider")+"</TD>");
out.print("<TD>"+rs.getString("info")+"</TD>");
out.print("<TD>"+rs.getString("stock")+"</TD>");
out.print("<TD>"+rs.getString("price")+"</TD>");
out.print("</TR>");
out.print("</TABLE>");
rs.close();
statement.close();
connection.close();
}
catch(SQLException e)
{
out.print(e.toString());
}
%>
</HTML>
</BODY>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -