JDBCTemplate-介绍
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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)