1.连接池连接数据库,DBCP数据源的两个jar包:
commons-dbcp.jar
commons-pool.jar
此外,如果使用的包是2.0以上的,使用时还需再下载commons-logging.jar(没有这个会报错)
2.讲jar包放进lib目录,并且把lib标记为库
3.创建一个db.properties文件,把配置信息写入(注意:3306/后面接的是数据库名称,除了这些配置以外,还可设置,initialSize、maxActive等参数)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=mysql123456
4.编写类返回数据库链接
package Lab13.utils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class Jdbcutils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
private static DataSource dataSource = null;
static {
try {
InputStream in = Jdbcutils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
dataSource = BasicDataSourceFactory.createDataSource(properties);
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getconn()throws
SQLException{
// return DriverManager.getConnection(url,username,password);
return dataSource.getConnection();
}
public static void release(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
5.使用
con = Jdbcutils.getconn();返回数据库连接
Jdbcutils.release(con,sql,res);关闭资源