JDBCTemplate-介绍
spring框架对JDBC的简单封装 提供了一个JDBCTemplate对象简化JDBC的开发
步骤
1.导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
2.创建JDBCTemplate对象 依赖于数据源DataSource
jdbcTemplate template = new jdbcTemplate(ds);
3.调用jdbcTemplate的方法来完成CRUD的操作
update():执行DML语句 增 删 改语句 queryForMap():查询结果将结果集封装为map集合 queryForList():查询结果将结果封装为list集合 query():查询结果 将结果封装为javaBean对象 queryForobject:查询结果 将结果封装为对象
代码
public static void main(String[] args) {
//1.创建JDBCTemplate对象
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//2.调用方法
String sql="update account set balance = 500 where id=?";
int count=template1.update(sql,2);
System.out.println(count);
}
JDBCUtils类
public class JDBCUtils {
//定义成员变量 DataSource
private static DataSource ds;
static {
try {
//1.加载配置文件
Properties pro = new Properties();
pro.load(JdkXmlUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 释放资源
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 获取连接方法
*/
public static DataSource getDataSource(){
return ds;
}
}

浙公网安备 33010602011771号