package common; import org.apache.commons.dbcp2.BasicDataSourceFactory; import javax.sql.DataSource; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * 这是一个数据库工具类,创建了一个数据库连接池 * 需要在database.properties中配置数据库连接属性 * @author Awin-x */ public class DBTool { static final DataSource ds; static{ Properties prop = new Properties(); try { InputStream database_info = DBTool.class.getClassLoader().getResourceAsStream("database.properties"); if (database_info != null) { prop.load(new InputStreamReader(database_info, "GBK")); prop.list(System.out); }else{ throw new FileNotFoundException("database.properties file does not exist in the classpath"); } } catch (IOException e) { System.out.println("数据库配置加载失败!"); throw new RuntimeException(e); } try { ds = BasicDataSourceFactory.createDataSource(prop); } catch (Exception e) { System.out.println("数据库连接池初始化失败"); throw new RuntimeException(e); } } public static Connection getConnection(){ try{ return ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); return null; } } public static PreparedStatement getPreparedStatement(String sql) throws SQLException{ //noinspection SqlSourceToSinkFlow return ds.getConnection().prepareStatement(sql); } public static void close(Connection conn, PreparedStatement ps, ResultSet rs){ try{ if(rs != null){ rs.close(); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { System.out.println("关闭失败"); e.printStackTrace(); } } public static void close(PreparedStatement ps, ResultSet rs) throws SQLException { close(ps.getConnection(), ps, rs); } public static void close(PreparedStatement ps) throws SQLException { close(ps.getConnection(), ps, null); } }