jdbc tomcat pool setting

在tomcat 設定tomcat jdbc pool需要作以下這幾件事情
1.在tomcat目錄下找到lib資料夾將mysql.jar(https://mvnrepository.com/artifact/mysql/mysql-connector-java)丟進去
2.配置web.xml相關參數請看https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes
3.配置context.xml
4.設定連結資料庫的LocalhostConnection檔

另外要自己件資料庫喔不然連不上(廢話)


設置web.xml
Resource需設置在GlobalNamingResources內
  <GlobalNamingResources>
 <Resource
 auth="Container"
 driverClassName="com.mysql.jdbc.Driver"
 url="jdbc:mysql://localhost:3306"
 connectionProperties="characterEncoding=utf8;useUnicode=true;autoReconnect=true"
 name="jdbc/localhost"
 username="root"
 password="1234"
 minIdle="1"
 initialSize="1"
 maxIdle="40"
 maxActive="50"
 maxWait="30000"
 minEvictableIdleTimeMillis="30000"
 factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
 jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
 jmxEnabled="true"
 logAbandoned="false"
 removeAbandoned="true"
 removeAbandonedTimeout="120"
 testOnBorrow="true"
 testOnReturn="false"
 testWhileIdle="true"
 timeBetweenEvictionRunsMillis="5000"
 type="javax.sql.DataSource"
 validationInterval="60000"
 validationQuery="SELECT 1"
 validationQueryTimeout="10"
/>
  </GlobalNamingResources>

設置context.xml
<Context>
<ResourceLink global="jdbc/localhost" name="jdbc/localhost" type="javax.sql.DataSource" />
</Context>

設置取得連線LocalhostConnection.java檔

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class LocalhostConnection {
  static public Connection getConnection() throws NamingException, SQLException {
    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource) envContext.lookup("jdbc/localhost");
    Connection con = ds.getConnection();
    con.setCatalog("mysql");
    return con;
  }
}

留言

這個網誌中的熱門文章

[java]BIG5 字集判斷

[java]半型轉全型

[javascript]當月第一天、當月最後一天