在Tomcat 5.5.4中配置JDBC数据源

mysql> select * from users;

+----+-------+------------+----------------+
| id | name | password | createTime |
+----+-------+------------+----------------+
| 1 | bitan | bbbbbbbbb | 20050202035511 |
| 2 | helen | hhhhhhhhh | 20050202035526 |
| 3 | susan | ssssssssss | 20050202035541 |
+----+-------+------------+----------------+
3 rows in set (0.00 sec)

K:\tomcat\conf\server.xml

……

<Context path="/test26" docBase="K:\test26" workDir="K:\test26\j2src" reloadable="true" debug="0">

<Resource name="jdbc/mydata" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mydata"/>

</Context>

</Host>

</Engine>

</Service>

</Server>

K:\test26\WEB-INF\web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!--与server.xml中的相关内容相互印证-->
<resource-ref>
<description>aaaaaaaaaaaaaaaa</description>
<res-ref-name>jdbc/mydata</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>


</web-app>

K:\test26\jndi.jsp

<%@ page contentType="text/html;charset=GBK" %>
<%@ page import="java.sql.*"%>
<%
try {
javax.naming.InitialContext ic = new javax.naming.InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) ic.lookup("java:comp/env/jdbc/mydata");//JNDI名字在web.xml和server.xml中设置

Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while(rs.next()) {
out.println(rs.getString(2) + ", " + rs.getString(3) + "<br>");
}
} catch (javax.naming.NamingException ne) {
out.println(ne.getMessage());
} catch (java.sql.SQLException se) {
out.println(se.getMessage());
}
%>

结果:

bitan, bbbbbbbbb
helen, hhhhhhhhh
susan, ssssssssss

你可能感兴趣的:(sql,tomcat,mysql,jdbc,SQL Server)