Data Source URL: jdbc:mysql://localhost:3306/mysql (注意此处不要填错,这个问题花了我不少时间,3306后面是“/”,而不是“?”,mysql是数据库名字)
JDBC Driver Class:
User Name: root
Password: ******
Max. Active Connections: 4
Max. Idle Connections: 2
Max. Wait for Connection: 5000
Validation Query:
输完后,成后点击\"save\"。记得要再点击上面的\"Commit Changes\"。这时查看server.xml文件可以看到多了两个<Resource/>元素,内容如下:
name="jdbc/mysql"
type="javax.sql.DataSource"
maxActive="4"
maxIdle="2"
username="root"
maxWait="5000"
driverClassName="com.mysql.jdbc.Driver"
password="yqs2602555"
url="jdbc:mysql://localhost/mysql"/>
<Resource
auth="Container"
description="User database that can be updated and saved"
name="UserDatabase"
type="org.apache.catalina.UserDatabase"
pathname="conf/tomcat-users.xml"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"/>
auth="Container"
description="User database that can be updated and saved"
name="jdbc/mysql"
type="javax.sql.DataSource"
username="root"
maxActive="4"
maxIdle="2"
maxWait="5000"
driverClassName="com.mysql.jdbc.Driver"
password="yqs2602555"
url="jdbc:mysql://localhost/mysql"/>
<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>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
final String JNDINAME = "java:comp/env/jdbc/mysql";
%>
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup(JNDINAME);
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from article");
while(rs.next()) {
out.println(rs.getString("title"));
}
} catch(Exception e) {
e.printStackTrace();
}
%>
<%
try {
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
%>