将JDBCUtils工具类改成Druid实现
public class Druid {
private static DataSource ds;
//在静态代码块中完成初始化
static {
try {
//创建Properties
Properties properties = new Properties();
properties.load(new FileInputStream("src/druid.properties"));
//创建一个指定参数的数据库连接池
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//获得连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接--在数据库连接池技术中,close 不是真正的断掉连接,而是使用Connection对象将连接放回连接池中
// 可能需要关闭的资源resultSet,statement或者PreperedStatement,Connectin
public static void close(ResultSet set, Statement statement, Connection connection) {
try {
if (set != null) {
set.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
//将编译异常转成运行异常,调用者可以选择捕获该异常,也可以选择默认处理
throw new RuntimeException(e);
}
}
}
测试
public class UseDruid {
public static void main(String[] args) {
}
@Test
public void update() throws Exception {
// 得到连接
Connection connection = Druid.getConnection();
// 组织sql语句
String update="update actor set `name`=? where id=?";
// 创建PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(update);
//给占位符赋值
preparedStatement.setString(1,"新关晓彤");
preparedStatement.setInt(2,3);
// 执行Sql
preparedStatement.executeUpdate();
// 关闭连接
Druid.close(null,preparedStatement,connection);
}
@Test
public void insert() throws Exception {
// 得到连接
Connection connection = Druid.getConnection();
// 组织sql语句
String insert="INSERT INTO actor VALUES(NULL,?,?,?,?)";
// 创建PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(insert);
//给占位符赋值
preparedStatement.setString(1,"李四");
preparedStatement.setString(2,"男");
preparedStatement.setString(3,"1999-08-04");
preparedStatement.setString(4,"114");
// 执行Sql
preparedStatement.executeUpdate();
// 关闭连接
Druid.close(null,preparedStatement,connection);
}
@Test
public void delete() throws Exception {
// 得到连接
Connection connection = Druid.getConnection();
// 组织sql语句
String delete="delete from actor where id=?";
// 创建PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(delete);
//给占位符赋值
preparedStatement.setInt(1,2);
// 执行Sql
preparedStatement.executeUpdate();
// 关闭连接
Druid.close(null,preparedStatement,connection);
}
@Test
public void select() throws Exception {
// 得到连接
Connection connection = Druid.getConnection();
// 组织sql语句
String select="select id,name from actor";
// 创建PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(select);
// 执行Sql
ResultSet resultSet = preparedStatement.executeQuery();
//将查询结果打印到控制台
while(resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
System.out.println(id+"\t"+name);
}
// 关闭连接
Druid.close(null,preparedStatement,connection);
}
}