使用Druid连接池连接数据库,首先先写配置资源,同时需要导druid-1.1.10.jar包
以及数据库驱动mysql-connector-java-8.0.15.jar包
driverClassName=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/表名称?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&rewriteBatchedStatements=trueusername=数据库用户名password=数据库密码initialSize=10maxActive=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);}