jsp文件在eclipse中运行需要tomcat服务器支持,运行后是网页的形式。
程序如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%> <!-- 导入的mysql驱动包 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>读取数据库结果 - My JSP starting page</title>
</head>
<body>
<%!
public static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
public static final String DBURL = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false" ;
public static final String DBUSER = "root" ;
public static final String DBPASS = "123456" ;
%>
<%
Connection conn = null ;
PreparedStatement pstmt = null ;
ResultSet rs = null ;
%>
<%
try{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT * FROM test" ;
pstmt = conn.prepareStatement(sql) ;
rs = pstmt.executeQuery() ;
%>
<center>
<table border="1" width="80%">
<tr>
<td>雇员编号</td>
<td>雇员姓名</td>
<td>雇员工作</td>
</tr>
<%
while(rs.next()){
int empno = rs.getInt(1) ;
String ename = rs.getString(2) ;
String job = rs.getString(3) ;
%>
<tr>
<td><%=empno%></td>
<td><%=ename%></td>
<td><%=job%></td>
</tr>
<%
}
%>
</table>
</center>
<%
}catch(Exception e) {
System.out.println(e) ;
}finally{
rs.close() ;
pstmt.close() ;
conn.close() ; // 如果直接关闭连接也可以
}
%>
</body>
</html>
运行结果 :
读取云服务器上的数据库数据程序:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%> <!-- 导入的mysql驱动包 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>读取数据库结果 - My JSP starting page</title>
</head>
<body>
<%!
public static final String DBDRIVER = "com.mysql.jdbc.Driver" ;
public static final String DBURL = "jdbc:mysql://111.230.224.15/animal?useUnicode=true&characterEncoding=utf-8&useSSL=false" ;
public static final String DBUSER = "root" ;
public static final String DBPASS = "123456" ;
%>
<%
Connection conn = null ;
PreparedStatement pstmt = null ;
ResultSet rs = null ;
%>
<%
try{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT * FROM testuser" ;
pstmt = conn.prepareStatement(sql) ;
rs = pstmt.executeQuery() ;
%>
<center>
<table border="1" width="80%">
<tr>
<td>雇员编号</td>
<td>雇员姓名</td>
</tr>
<%
while(rs.next()){
int empno = rs.getInt(1) ;
String ename = rs.getString(2) ;
%>
<tr>
<td><%=empno%></td>
<td><%=ename%></td>
</tr>
<%
}
%>
</table>
</center>
<%
}catch(Exception e) {
System.out.println(e) ;
}finally{
rs.close() ;
pstmt.close() ;
conn.close() ; // 如果直接关闭连接也可以
}
%>
</body>
</html>