本次实验以mysql数据库为例 一、配置 (1、进入GlassFish控制台 -》 资源 -》 JDBC连接池 新建连接池 池名称:mywork 资源类型:javax.sql.DataSource 数据源类名称:com.mysql.jdbc.jdc2.optional.MysqlDataSource portNumber:3306 databaseName:mywork serverName:127.0.0.1 user:root password:xxxxxx (2、GlassFish控制台 -》 资源 -》 JDBC资源 新建资源 JNDI名称:jdbc/mywork 池名称:mywork (3、添加jdbc对特定数据库的驱动 mysql-connector-java-5.0.4-bin.jar (通常在mysql安装目录下可以找到) 放置到:glassfish-3.1.2.2\glassfish\domains\domain1\lib 二、使用 import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; ResultSet rs = null; Statement stmt = null; Connection conn = null; try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SaveIP</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet SaveIP at " + request.getContextPath() + "</h1>"); out.println("<ul>"); String strJNDIName = "jdbc/ytestpool"; Context initialcontext = new InitialContext(); DataSource datasource = (DataSource) initialcontext.lookup(strJNDIName); conn = datasource.getConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery("select * from ipwork"); while (rs.next()) { //out.println(rs.getString("user_name")); out.println("<li>" + rs.getString("clientname") + "===>>"+ rs.getString("ip") + "</li>"); } out.println("</ul>"); out.println("</body>"); out.println("</html>"); } catch (Exception e) { System.out.println(e.toString()); } finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch(SQLException sqlex) { System.out.println(sqlex.getMessage()); } out.close(); }