📄 testdatasource.jsp
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ page
language="java"
contentType="text/html; charset=GB2312"
pageEncoding="GB2312"
import="java.sql.*,javax.sql.*"
%>
<META http-equiv="Content-Type" content="text/html; charset=GB2312">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="../theme/Master.css" rel="stylesheet" type="text/css">
<TITLE>testDatasource.jsp</TITLE>
</HEAD>
<BODY>
<h2>测试通过数据源连接数据库</h2>
<table border=1>
<%
java.sql.Connection connection = null;
java.sql.ResultSet rs = null;
try {
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
// 获得数据源
javax.sql.DataSource datasource =
(javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/eshop");
// 从数据源获得一个连接
connection = datasource.getConnection();
// create a query from the connection
java.sql.Statement statement = connection.createStatement();
//创建表,并且把数据插入到表中。
statement.execute("drop table testtable");
statement.execute("create table testtable(id int,name varchar(20))");
statement.executeUpdate("insert into testtable values(1,'xiaofei2')");
statement.executeUpdate("insert into testtable values(2,'zhangsan')");
//从表中查询数据
rs = statement.executeQuery("select * from testtable");
while (rs.next()) {
out.println("<tr>");
out.println("<td>"+rs.getString("id")+"</td>");
out.println("<td>"+rs.getString("name")+"</td>");
out.println("</tr>");
}
out.println("</table>");
rs.close();
connection.close();
} catch (javax.naming.NamingException e) {
out.println("Name not found!");
out.println(e);
} catch (java.sql.SQLException e) {
System.out.println("SQLException!");
System.out.println(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
System.out.println(
"Failed to close the ResultSet after the failure");
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println(
"Failed to close the connection after the failure");
}
}
}
%>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -