在web下新建web-inf文件
在web-inf下新建lib文件导入:commons-dbutils-1.7.jar
druid-1.1.5.jar
mysql-connector-java-5.1.32.jar
导入以上三个包—add-library
src-com.anbow.jsp.User(新建一个实体类)
public class DruidUtils {
//Druid德鲁伊,据说是魔兽世界中的一个角色,森林女神
public static DruidDataSource dataSource;//数据库连接池
//1.初始化Druid连接池
static {
//第二种方式:使用软编码通过配置文件初始化
try {
Properties properties = new Properties();
//通过类加载器加载配置文件
InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(inputStream);
//创建连接池
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//2.获取连接
public static Connection getConnection() {
try {
return dataSource.getConnection();//从连接池中获取连接
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static DataSource getDataSource(){
return dataSource;
}
//3.释放资源
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
//释放resultSet
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
//释放Statement
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
//释放Connection
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}