配置了yml文件
package com.tylin.erpreport.util; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.core.io.ClassPathResource; import java.io.InputStream; import java.sql.*; public class SqlServerDruidUtil { private static String DBDRIVER = null;// 驱动类类名 private static String DBURL = null; private static String DBUSER = null; private static String DBPASSWORD = null; static{ try { ClassPathResource resource = new ClassPathResource("application.yml"); InputStream inputStream = resource.getInputStream(); YamlUtils.setYmlInputSteam(inputStream); String profileActive = YamlUtils.getByKey("spring.profiles.active").toString(); resource = new ClassPathResource("application-"+profileActive+".yml"); inputStream = resource.getInputStream(); YamlUtils.setYmlInputSteam(inputStream); DBDRIVER = YamlUtils.getByKey("spring.datasource.driverClassName").toString(); DBURL = YamlUtils.getByKey("spring.datasource.url").toString(); DBUSER = YamlUtils.getByKey("spring.datasource.username").toString(); DBPASSWORD = YamlUtils.getByKey("spring.datasource.password").toString(); }catch (Exception e){ throw new RuntimeException("SqlServerUtil static Exception "+e.getMessage()); } } public SqlServerDruidUtil(){ } public static Connection getConnection()throws Exception { Connection conn = null; DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(DBDRIVER); dataSource.setUrl(DBURL); dataSource.setUsername(DBUSER); dataSource.setPassword(DBPASSWORD); conn = dataSource.getConnection(); return conn; } public static ResultSet executeQuery(String sql) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); // 执行sql: rs = pstmt.executeQuery(); return rs; } catch (SQLException sqle) { throw new SQLException("select data Exception: " + sqle.getMessage()); } catch (Exception e) { throw new Exception("System error: " + e.getMessage()); }finally { closeConnection(null, pstmt, conn); } } public static void executeUpdate(String sql) throws Exception { PreparedStatement ps = null; Connection conn = null; try { conn =getConnection(); ps = conn.prepareStatement(sql); ps.executeUpdate(); } catch (SQLException sqle) { throw new SQLException("select data Exception: " + sqle.getMessage()); } catch (Exception e) { throw new Exception("System error: " + e.getMessage()); }finally { closeConnection(null, ps, conn); } } public static void closeConnection(ResultSet rs, PreparedStatement ps, Connection conn){ try { if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if(conn!=null){ conn.close(); } }catch (SQLException e){ e.printStackTrace(); } } }