1 import java.io.FileNotFoundException; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.sql.SQLException; 5 import java.util.Properties; 6 7 import javax.sql.DataSource; 8 9 import com.alibaba.druid.pool.DruidDataSourceFactory; 10 11 public class JDBCUtils 12 { 13 protected static DataSource ds; 14 15 static 16 { 17 try 18 { 19 Properties properties = loadPropertyFile("druid.properties"); 20 ds = DruidDataSourceFactory.createDataSource(properties); 21 } 22 catch (Exception e) 23 { 24 e.printStackTrace(); 25 } 26 } 27 28 public static Properties loadPropertyFile(String fileName) 29 { 30 if (null == fileName || fileName.equals("")) 31 { 32 throw new IllegalArgumentException("Properties file path can not be null: " + fileName); 33 } 34 35 InputStream inputStream = null; 36 Properties properties = null; 37 try 38 { 39 inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream(fileName); 40 properties = new Properties(); 41 properties.load(inputStream); 42 } 43 catch (FileNotFoundException e) 44 { 45 throw new IllegalArgumentException("Properties file not found: " + fileName); 46 } 47 catch (IOException e) 48 { 49 throw new IllegalArgumentException("Properties file can not be loading: " + fileName); 50 } 51 finally 52 { 53 try 54 { 55 if (inputStream != null) 56 { 57 inputStream.close(); 58 } 59 } 60 catch (IOException e) 61 { 62 e.printStackTrace(); 63 } 64 } 65 return properties; 66 } 67 68 /** 69 * 获得数据源 70 * 71 * @return 72 */ 73 public static DataSource getDataSource() 74 { 75 return ds; 76 } 77 78 public static void closeConnection() throws SQLException 79 { 80 if (ds != null && ds.getConnection() != null && !ds.getConnection().isClosed()) 81 { 82 ds.getConnection().close(); 83 } 84 } 85 }