Tomcat连接Mysql测试样例
首先在mysql中建立如图数据库:
1、
修改contex.xml文件:
<Context>
<Resource name="jdbc/mysql" auth="Container"
type="javax.sql.DataSource"
maxActive="50" maxIdle="10" maxWait="5000"
username="root" password="bobo365"
driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost/test1" />
</Context>
2、
修改web.xml文件:
<web-app>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
3、
测试文档test.jsp:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>mysql test page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
out.print("My data test:<br>");
DataSource ds = null;
try{
InitialContext ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
String strSql = " select * from pet";
ResultSet rs = stmt.executeQuery(strSql);
while(rs.next()){
out.print("name:" + rs.getString(1));
out.print("\towner:" + rs.getString(2));
out.print("\tbirth:" + rs.getString("birth"));
out.println("<br>");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
%>
</body>
</html>
4、显示样式:
//////////////////////////////////////////////////////////////
启开tomcat管理界面。
1、更改配置文件:context.xml
转载于:https://blog.51cto.com/bobo365/1892464