1、在context中定义数据源
1 25 17 1816
2、在web.xml中配置
1 26 testDs 78 11testServlet 9test_servlet_package.test_servlet 1012 15testServlet 13/testServlet 1416 21DB Connection 17jdbc/mysql 18javax.sql.DataSource 19Container 20
3、在servlet中使用
1 package test_servlet_package; 2 import java.io.IOException; 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.Statement; 6 import javax.naming.InitialContext; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 import javax.sql.DataSource;12 public class test_servlet extends HttpServlet {13 14 protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {15 DataSource ds = null;16 try {17 InitialContext ctx = new InitialContext();18 ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");19 Connection conn = ds.getConnection();20 Statement stmt = conn.createStatement();21 String strSql = "select * from dim_code";22 ResultSet rs = stmt.executeQuery(strSql);23 while (rs.next()) {24 System.out.println("name:" + rs.getString(1));25 }26 rs.close();27 stmt.close();28 conn.close();29 } catch (Exception ex) {30 ex.printStackTrace();31 }32 }33 }
总结:案例只是介绍一个数据源的简单使用、用于理解、方便后期调查使用