Tomcat 6データ接続プール構成


1.context.xmlでデータ接続ソースを構成し、データベースドライバをlibディレクトリにコピー

<!--    -->
	<Resource name="jdbc/Datasource"
			  auth="Container"
			  type="javax.sql.DataSource"
			  driverClassName="com.mysql.jdbc.Driver"
			  url="jdbc:mysql://localhost:3306/test"
			  username="root"
			  password="****"
			  maxActive="100"
			  maxIdle="30"
			  maxWait="1000"
		/>


2.サーブレットでInitialContext lookupからDataSourceへのデータベース操作

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        System.out.println("doget........");
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/Datasource");
            Connection conn = ds.getConnection();
            System.out.println("connection: " +conn);

            String userName=request.getParameter("userName");
            String password = request.getParameter("password");

            String sql = "insert into user(name,password) value('"+userName+"','"+password+"')";
            System.out.println(sql);
            Statement st = conn.createStatement();
            st.execute(sql);
            conn.close();
           
        } catch (SQLException ex) {
            Logger.getLogger(JDBCTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(JDBCTest.class.getName()).log(Level.SEVERE, null, ex);
        }

    }