meta-inf下建context.xml文件
加入以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/access"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="libaoan"
password="libaoan1212"
driverClassName="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:langshengDS" />
</Context>
访问LoginDao文件
package com.langsheng.dao;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class LoginDao{
public String access() throws Exception{
Connection conn = null;
DataSource ds = null;
ResultSet rs = null;
Statement stmt = null;
//连接池的获取
try{
Context initCtx = new InitialContext();
ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/access");
conn = ds.getConnection();
}catch(Exception e){
e.printStackTrace();
return "ERROR";
}
if (ds != null) {
try {
stmt = conn.createStatement();
//执行一条select查询sql语句后得到的表格存入ResultSet对象中
String sql="select * from user;
rs=stmt.executeQuery(sql);
if(rs.next()==false){
return "input";
}else{
return "success";
}
}
catch(SQLException e){
e.printStackTrace();
return "ERROR";
}catch(Exception e){
}
finally{
//关闭所有相关连接
try{
if(rs!=null)conn.close();
if(stmt!=null)conn.close();
if(conn!=null)conn.close();
}catch(Exception e){
e.printStackTrace();
return "ERROR";
}
}
}
System.out.println("ERROR");
return "ERROR";
}
}