DBCP 数据库连接池JNDI连接 学习笔记
数据库连接池:减少数据库连接的数量提高数据库访问效率
DBCP优点:
1\速度快
2\tomcat 都默认使用DBCP,說明大众!
3\连接数控制与连接归还策略
4\应对网络不稳定的策略
5\应对连接泄漏的策略
测试环境:MyEclipse 6.5+ tomcat 6.0+ Sybase ase
1、加入DBCP包:commons-dbcp-1.4.jar jconn3.jar
2\在tomcat content.xml 中加入
<Resource name="/jdbc/resourceName"
type="javax.sql.DataSource"
driverClassName="com.sybase.jdbc3.jdbc.SybDataSource"
url="jdbc:sybase:Tds:127.0.0.1:4001/amls"
username=""
password=""
maxActive="40"
maxIdle="2"
maxWait="50000" />
3\修改项目的web.xml
<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the
configurartion for the web application.
</description>
<res-ref-name>
amls
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
4\ java 调用JNDI
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.handson.dao.UserDao;
import com.handson.dto.User;
public class ConnectionProvider {
private static DataSource ds = null;
static{
try {
Context c = new InitialContext();
ds = (DataSource) c.lookup("java:/comp/env/jdbc/resourceName"); //此处默认需要加/comp/env,可以进行设置不加!
} catch (NamingException e) {
e.printStackTrace();
}
}
//以下为JDBC连接!
//Class.forName(driverName);
// Connection dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
public static Connection getConnection(){
if(ds != null){
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
}
5 获取连接JAVA:
package com.handson.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.handson.dbcp.*;
import com.handson.dto.User;
public class UserDao {
private Connection con;
public User findUserByUserName(String userName){
con = ConnectionProvider.getConnection();
String sql = "select * from userInfo where Username = ?";
PreparedStatement pst = null;
ResultSet rs = null;
User user = null;
try {
pst = con.prepareStatement(sql);
pst.setString(1, userName);
rs = pst.executeQuery();
if(rs.next()){
user = new User();
user.setHost(rs.getString("Host"));
user.setUser(rs.getString("Username"));
user.setPassword(rs.getString("Password"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
6测试JSP:
<body>
<% UserDao dao = new UserDao();
User user=dao.findUserByUserName("root");
out.println("Host:"+user.getHost()+"<br>");
out.println("User:"+user.getUser()+"<br>");
out.println("Password:"+user.getPassword()+"<br>");