Tomcat+mysql連接池配置


View Code
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
    <Resource name="jdbc/mysql" 
auth="Container" 
type="javax.sql.DataSource" 
maxActive="50" 
maxIdle="10" 
maxWait="5000" 
username="root" 
password="sql123" 
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/labtmp?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull" />
</Context>

 

View Code
package com.my;

import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import javax.sql.*;
import javax.naming.*;

public class Mysql {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private Statement stm = null;

    // constructor 1
    public Mysql() throws Exception {
             
        conn=lookForConnection();
        if(conn!=null)
           stm = conn.createStatement();
        else
           System.out.println("get DB Connection Failure!");
    }

    // constructor 2
    public Mysql(String sql) throws Exception {
        conn=lookForConnection();  
         if(conn!=null)
         {   
             this.prepareStatement(sql);
             stm = conn.createStatement();
         }
         else
             System.out.println("get DB Connection Failure!");
    }
    
    private Connection lookForConnection()throws Exception
    {
        DataSource ds = null; 
         try{ 
             InitialContext ctx=new InitialContext(); 
             ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql"); 
             Connection con= ds.getConnection();  
             return con;
         }
        catch(Exception ex){
             ex.printStackTrace();
             return null;
        } 
    }
    public void prepareStatement(String sql) throws SQLException {
        ps = conn.prepareStatement(sql);
    }

    public void clearParameters() throws SQLException {
        ps.clearParameters();
    }

    // return the connection object
    public Connection getConnection() {
        return conn;
    }

    // return the preparedstatement
    public PreparedStatement getPreparedStatement() {
        return ps;
    }

    // return the set of query
    public ResultSet executeQuery(String sql) throws SQLException {
        if (stm != null) {
            return stm.executeQuery(sql);
        } else
            return null;
    }

    // return the set of query
    public ResultSet executeQuery() throws SQLException {
        if (ps != null) {
            return ps.executeQuery();
        } else
            return null;
    }

    // execute the operation of update
    public void executeUpdate(String sql) throws SQLException {
        if (stm != null)
            stm.executeUpdate(sql);
        else
           System.out.println("the Statement is null");
    }

    // execute the operation of update
    public void executeUpdate() throws SQLException {
        if (ps != null)
        {
          ps.executeUpdate();
        }
        else
            System.out.println("the prepareStatement is null");   
    }

    // close the connection and free resource
    public void closeCon() throws SQLException {
        if (stm != null) {
            stm.close();
            stm = null;
        }
        if (ps != null) {
            ps.close();
            ps = null;
        }
        conn.close();
        conn = null;
    }

    // lock the table
    public boolean lockTable(String table, String privilege)throws SQLException {
        String locksql = "lock tables " + table + " " + privilege;
            if(this.executeQuery(locksql)!=null)
            {
                // System.out.println("lock");
                return true;
            }
            else
            return false;
    }

    // unlock the table
    public boolean unLockTable() throws SQLException{
        String unlocksql = "unlock tables ";
        if(this.executeQuery(unlocksql)!=null)
        {
            // System.out.println("unlock");
            return true;
        }
        else
            return false;
    }

    // set the parameter
    public void setString(int index, String value) throws SQLException {
        ps.setString(index, value);
    }

    public void setInt(int index, int value) throws SQLException {
        ps.setInt(index, value);
    }

    public void setBoolean(int index, boolean value) throws SQLException {
        ps.setBoolean(index, value);
    }

    public void setDate(int index, Date value) throws SQLException {
        ps.setDate(index, value);
    }

    public void setLong(int index, long value) throws SQLException {
        ps.setLong(index, value);
    }

    public void setFloat(int index, float value) throws SQLException {
        ps.setFloat(index, value);
    }
    public void setBinaryStream(int index,InputStream in,int length) throws SQLException {
        ps.setBinaryStream(index,in,length);
        }
}

 

我的環境:

 Tomcat7.0.22,Mysql5.5,Windows xp Sp3

 最近需要在tomcat下配置mysql的連接池,在網上找了些資料參考了下,不同的版本tomcat配置介紹都略有不同,下面我介紹一下我配置的方法。

 1.首先,要安裝JDK1.6,Tomcat,mysql等,這些就不在此多說了。

  值得注意的是,mysql表字符集設置,很有可能在客戶端和JSP中亂碼,可參考文章:

  http://c02949.blog.163.com/blog/static/485037200962345218147/ 

  我是在eclipse下布署運行Tomcat的,在eclipse的window-->preference--->Server里,右面的里面添加tomcat的路徑,指定jdk,然后在下面的servers選項卡里新建一個服務器,這時候就會在eclipse的project explore中生成一個Servers項目

 

 

   2.在context.xml的<context></context>之間添加連接池如下:

 <Resource name="jdbc/mysql"

auth="Container" 
type="javax.sql.DataSource" 
maxActive="50"

maxIdle="10"

maxWait="5000" 
username="你的mysql用戶"

password="你的mysql密碼" 

driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/dbname?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull
"/>

<WatchedResource>WEB-INF/web.xml </WatchedResource>  

XML里 & 要用&amp ;替代,不然會被過濾掉。

 

配置文件中Resource標簽中各屬性的含義:

driverClassName - JDBC 所用到的數據庫驅動的類全名.

maxActive - 連接池在同一時刻內所提供的最大活動連接數。

maxIdle - 連接池在空閑時刻保持的最大連接數.

maxWait - 當發生異常時數據庫等待的最大毫秒數 (當沒有可用的連接時).

password - 連接數據庫的密碼.

url - 連接至驅動的URL. (為了向后兼容, DRIVERNAME也被允許.)

username - 數據庫用戶名.

各種配置方式的范圍也應該是不一樣的。我在這就不細說了,總之就是在Context標簽下面配置個Resource標簽即可。

 

我的配置:

最后,將mysql 的jdbc驅動復制到配置tomcat下的lib目錄;

OK,到此tomcat就配置完了,接下來就是新建工程,測試:

3.打開Eclipse其手工建個WEB project(我的工程名AJAX),加入mysql JDBC驅動(我的這步沒加入也可以正常運行);

配置WEB-INFO下面的web.xml文件:

<web-app></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>

 我的配置:

View Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>AJAX</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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>

 

注意的地方: context.xml文件中的name="jdbc/mysql"要和web.xml中的<res-ref-name>jdbc/mysql</res-ref-name>要一致;

新建JSP文件:

View Code
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%> 
<%@ page import="javax.sql.*"%> 
<%@ page import="javax.naming.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
<title>mysql連接池測試</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
   </head>
  
   <body> 
<%  
out.print("我的測試開始<br>"); 
DataSource ds = null; 
Connection conn=null;
       try{ 
InitialContext ctx=new InitialContext(); 
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql"); 
conn = ds.getConnection();  

    }catch(Exception ex){
     ex.printStackTrace();
    } 
%>  
<%   
    if(conn!=null){ 
%> 
     <%= conn %>;  
<% 
    } 
%> 
   </body>
</html>

 調試,運行,如果配置成功,則會在網頁中輸出以下內容:

這樣就配置完成了。

下面附上我寫的數據操作類(Mysql.java):

 

View Code
package com.my;

import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import javax.sql.*;
import javax.naming.*;

public class Mysql {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private Statement stm = null;

    // constructor 1
    public Mysql() throws Exception {
             
        conn=lookForConnection();
        if(conn!=null)
           stm = conn.createStatement();
        else
           System.out.println("get DB Connection Failure!");
    }

    // constructor 2
    public Mysql(String sql) throws Exception {
        conn=lookForConnection();  
         if(conn!=null)
         {   
             this.prepareStatement(sql);
             stm = conn.createStatement();
         }
         else
             System.out.println("get DB Connection Failure!");
    }
    
    private Connection lookForConnection()throws Exception
    {
        DataSource ds = null; 
         try{ 
             InitialContext ctx=new InitialContext(); 
             ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql"); 
             Connection con= ds.getConnection();  
             return con;
         }
        catch(Exception ex){
             ex.printStackTrace();
             return null;
        } 
    }
    public void prepareStatement(String sql) throws SQLException {
        ps = conn.prepareStatement(sql);
    }

    public void clearParameters() throws SQLException {
        ps.clearParameters();
    }

    // return the connection object
    public Connection getConnection() {
        return conn;
    }

    // return the preparedstatement
    public PreparedStatement getPreparedStatement() {
        return ps;
    }

    // return the set of query
    public ResultSet executeQuery(String sql) throws SQLException {
        if (stm != null) {
            return stm.executeQuery(sql);
        } else
            return null;
    }

    // return the set of query
    public ResultSet executeQuery() throws SQLException {
        if (ps != null) {
            return ps.executeQuery();
        } else
            return null;
    }

    // execute the operation of update
    public void executeUpdate(String sql) throws SQLException {
        if (stm != null)
            stm.executeUpdate(sql);
        else
           System.out.println("the Statement is null");
    }

    // execute the operation of update
    public void executeUpdate() throws SQLException {
        if (ps != null)
        {
          ps.executeUpdate();
        }
        else
            System.out.println("the prepareStatement is null");   
    }

    // close the connection and free resource
    public void closeCon() throws SQLException {
        if (stm != null) {
            stm.close();
            stm = null;
        }
        if (ps != null) {
            ps.close();
            ps = null;
        }
        conn.close();
        conn = null;
    }

    // lock the table
    public boolean lockTable(String table, String privilege)throws SQLException {
        String locksql = "lock tables " + table + " " + privilege;
            if(this.executeQuery(locksql)!=null)
            {
                // System.out.println("lock");
                return true;
            }
            else
            return false;
    }

    // unlock the table
    public boolean unLockTable() throws SQLException{
        String unlocksql = "unlock tables ";
        if(this.executeQuery(unlocksql)!=null)
        {
            // System.out.println("unlock");
            return true;
        }
        else
            return false;
    }

    // set the parameter
    public void setString(int index, String value) throws SQLException {
        ps.setString(index, value);
    }

    public void setInt(int index, int value) throws SQLException {
        ps.setInt(index, value);
    }

    public void setBoolean(int index, boolean value) throws SQLException {
        ps.setBoolean(index, value);
    }

    public void setDate(int index, Date value) throws SQLException {
        ps.setDate(index, value);
    }

    public void setLong(int index, long value) throws SQLException {
        ps.setLong(index, value);
    }

    public void setFloat(int index, float value) throws SQLException {
        ps.setFloat(index, value);
    }
    public void setBinaryStream(int index,InputStream in,int length) throws SQLException {
        ps.setBinaryStream(index,in,length);
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM