Java工具包之-Guava
function方法简化代码
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.qunar.fresh.bean.PageVistor;
import com.qunar.fresh.bean.dbBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import java.sql.*;
import java.util.List;
public class DbUtil<F, T> {
private static final String CONFIG_PROPERTIES = "classpath:Beans.xml";
static Logger logger = LoggerFactory.getLogger(DbUtil.class);
private Connection connection = null;
private static dbBean dataBean;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private List<PageVistor> PageVisitors;
static {
try {
BeanFactory beanFactory = new FileSystemXmlApplicationContext(CONFIG_PROPERTIES);
dataBean = (dbBean) beanFactory.getBean("dbBean");
Class.forName(dataBean.getDriver());
} catch (ClassNotFoundException e) {
logger.info(String.format("sql exception0 : %s", e));
}
}
private T execute(Function<F, T> function, String sql) {
T execResult = null;
try {
connection = DriverManager.getConnection(dataBean.getUrl(),
dataBean.getUsername(), dataBean.getPassword());
preparedStatement = connection.prepareStatement(sql);
execResult = function.apply(null);
} catch (SQLException e) {
logger.info(String.format("sql exception1 : %s", e));
} finally {
try {
if (!preparedStatement.isClosed())
preparedStatement.close();
if (!connection.isClosed())
connection.close();
} catch (SQLException e) {
logger.info(String.format("sql exception2 : %s", e));
}
}
return execResult;
}
public List<PageVistor> Query(String sql) {
PageVisitors = Lists.newArrayList();
Function<F, T> function = new Function<F, T>() {
@Override
public T apply(F input) {
try {
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
PageVisitors.add(new PageVistor(0, "", resultSet.getString(1)
, resultSet.getInt(2)));
}
} catch (SQLException e) {
logger.info(String.format("sql exception3 : %s", e));
} finally {
try {
if (resultSet != null) resultSet.close();
} catch (SQLException e) {
logger.info(String.format("sql exception4 : %s", e));
}
}
return null;
}
};
this.execute(function, sql);
return PageVisitors;
}
public void Update(String sql) {
Function<F, T> function = new Function<F, T>() {
@Override
public T apply(F input) {
try {
int var = preparedStatement.executeUpdate();
if (var == 0)
logger.error("{} 更新数据失败");
} catch (SQLException e) {
logger.info(String.format("sql exception3 : %s", e));
}
return null;
}
};
this.execute(function, sql);
}
}
https://blog.csdn.net/zmx729618/article/details/78540026
https://my.oschina.net/realfighter/blog/349831
https://blog.csdn.net/zmx729618/article/details/78540026