public class DruidUtil {
//初始化连接池
private static DataSource pool = null;
static {
//获取配置文件信息
InputStream in = null;
try {
in = new FileInputStream("day10\\src\\Druid.properties");
Properties properties = new Properties();
properties.load(in);
pool = DruidDataSourceFactory.createDataSource(properties);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() {
Connection connection = null;
try {
connection = pool.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//释放连接
public static void returnConnection(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class DruidTest {
@Test
public void Druid(){
//获取连接对象
Connection connection = DruidUtil.getConnection();
String sql = "select * from tb_student;";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString("sname"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放连接
DruidUtil.returnConnection(resultSet,preparedStatement,connection);
}
}
}