dbcp读取配置文件的方式:
1. 导入3个包:commons-dbcp-... .jar(数据源) commons-collections-.....jar(集合) commons-pool....jar(连接池) dbcp依赖 collections和pool
2.新建 *.properties属性文件,内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbName
username=root
password=root
#<!-- 初始化连接-->
initialSize=10
maxActive=50
minIdle=5
maxWait=5000
.
.
. 属性
3.创建通用连接:
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DbcpTool {
public static Connection dbcpWithDataSourceFactory() throws Exception{
Connection conn=null;
InputStream inputStream=DbcpTool.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties=new Properties();
properties.load(inputStream);
DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
conn=dataSource.getConnection();
return conn;
}
public static void close(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement prst){
try {
if(prst!=null){
prst.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement prst,Connection conn){
close(prst);
close(conn);
}
public static void close(ResultSet rs,PreparedStatement prst,Connection conn){
close(rs);
close(prst);
close(conn);
}
}