MySQL JDBC 连接池
1.首先声明一个连接池对象
private static DruidDateSource druidDateSource;
2.在获得字节流之后,在获取连接池的值
通过DruidDateSourceFactory.createDateSource方法获得
此方法接收的为一个properties集合,所以将之前的properties传入即可
DruidDateSourceFactory.createDateSource(properties);
3.将连接池对象赋值
由于连接池对象与此方法的返回值并不相同,所以需要进行强转类型
druidDateSource = (DruidDateSource)DruidDateSourceFactory.createDateSource(properties);
4.获取连接
druidDateSource.getconnection()
public class Dbutils { private static DruidDataSource druidDataSource; static { Properties properties = new Properties(); InputStream inputStream = Dbutils.class.getResourceAsStream("/datebase.properties"); try { properties.load(inputStream); try { druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() { try { return druidDataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } }