2013年5月22日 星期三

JDBC設定

1.記得裝SQL的Driver在WEB-INF下的lib
download Driver: http://www.mysql.com/products/connector/

2. 取得Data Source的JNDI設定 (與Context的look up有關)
在WEB-INF下的web.xml裡要加上
<resource-ref>
<res-ref-name>jdbc/aaa</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
這樣jdbc/aaa就會對應到javax,sql.DataSource

Context context= new InitialContext();
DataSource ds=context.lookup("java:/comp/env/jdbc/aaa");
才找得到

3.在WEB-INF下的web.xml設定:

  <Resource
    name="jdbc/mysql-aaa-bbb"
    auth="Container"
    type= "javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://127.0.0.1:3306/?characterEncoding=UTF-8"
    username="your_username"
    password="your_password"
    maxActive="2"
    maxIdle="2"
    minIdle="1"
    maxWait="10000"
    autoReconnect = "true"
     >
 </Resource>

在Servlet下連線:
private String connectResource= "java:/comp/env/jdbc/mysql-aaa-bbb";
Context ctx=null;
ctx=new InitialContext();
DataSource ds=(DataSource) ctx.lookup(connectResource);
Connection conn=null;
conn = ds.getConnection();
//query
String queryCommand="SELECT column FROM table ";
PreparedStatement ps=null;
ResultSet rs=ps.executeQuery();

沒有留言:

張貼留言