import org.springframework.jdbc.core.JdbcTemplate;
public class GAUtils {
private static JdbcTemplate jdbcTemplate;
private static final String driverClassName = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=UTF-8";
private static final String dbUser = "root";
private static final String dbPassword = "xxxx";
public static JdbcTemplate getJdbcTemplate() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(dbUser);
dataSource.setPassword(dbPassword);
// 或者从配置文件中获取数据库连接信息
/**
* 从配置文件中获取数据库配置信息
*/
InputStream inputStream = GAUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
Properties properties = new Properties();
try {
properties.load(inputStream);
String url = properties.getProperty("jdbc.url.jeecg");
String username = properties.getProperty("jdbc.username.jeecg");
String password = properties.getProperty("jdbc.password.jeecg");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//想要获取一个jdbcTemplate对象,只需要获取一个dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
本文介绍了一个使用Apache Commons DBCP和Spring JdbcTemplate实现的Java工具类,该工具类简化了数据库连接池的配置和JdbcTemplate实例的创建过程。通过从属性文件中读取数据库配置信息,提高了代码的灵活性。
795

被折叠的 条评论
为什么被折叠?



