导包
JdbcTemplate jar包
![包](https://i-blog.csdnimg.cn/blog_migrate/42d62a3a925466e0f3536fa859576458.jpeg)
Druid jar包
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bd93a1f8fd08ecaf6ce21d40e634343d.png)
书写Druid.properties配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/login
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
JDBCTemplate Utils工具类
package xxx
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtils {
private static DataSource ds;
static {
try {
Properties p = new Properties();
p.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(p);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接的对象的方法
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 释放资源的方法
* 适用于增删改
* @param pstmt
* @param conn
*/
public static void close(PreparedStatement pstmt,Connection conn){
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 释放资源的方法
* 适用于查
* @param rs
* @param pstmt
* @param conn
*/
public static void close(ResultSet rs,PreparedStatement pstmt,Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
close(pstmt,conn);
}
/**
* 获取=连接池的对象
* @return
*/
public static DataSource getPool(){
return ds;
}
}