//1. 拿到 druid 的数据源static DruidDataSource dataSource;//2. 读取配置文件 ,初始化数据源static {Properties properties = new Properties();InputStream is = DBHelper.class.getClassLoader().getResourceAsStream(\"jdbc.properties\");try {properties.load(is);dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);} catch (Exception e) {e.printStackTrace();}}//3. 拿到数据库连接对象public static Connection getConnection(){try {DruidPooledConnection conn = dataSource.getConnection();return conn;} catch (SQLException e) {e.printStackTrace();}return null;}//4. 资源释放 (适用于增删改)public static void close(Connection conn, PreparedStatement ps){try {if(conn!=null){conn.close();}if(ps!=null){ps.close();}} catch (SQLException e) {e.printStackTrace();}}public static void close(Connection conn, PreparedStatement ps, ResultSet rs){try {if(rs!=null){rs.close();}close(conn,ps);} catch (SQLException e) {e.printStackTrace();}}public static void main(String[] args) {System.out.println(getConnection());}
使用druid资源进行数据库链接
未经允许不得转载:爱站程序员基地 » 使用druid资源进行数据库链接