?使用Druid连接池连接数据库,首先先写配置资源,同时需要导druid-1.1.10.jar包
以及数据库驱动mysql-connector-java-8.0.15.jar包
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/表名称?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&rewriteBatchedStatements=true
username=数据库用户名
password=数据库密码
initialSize=10
maxActive=10
然后读取配置资源 ,加载驱动
public class DruidConn {
private static DataSource dataSource;
static {
try {
Properties pros = new Properties();
//读取文件配置资源
InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Druild.properties");
//加载驱动
pros.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(pros);
} catch (Exception e) {
e.printStackTrace();
}
}
//使用druid连接数据库
public static Connection getConnection3() {
Connection connection = null;
try {
connection = dataSource.getConnection();
return connection;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
最后关闭数据库连接池
public static void close(Connection connection, PreparedStatement preparedStatement){
DbUtils.closeQuietly(connection);
DbUtils.closeQuietly(preparedStatement);
}
|