💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
增删改用的是同一个方法`update`,只是需要改变 SQL 语句即可。下面以增为例,介绍几个常用的`update`方法。 <br/> **1. `int update(String sql, Map<String, ?> paramMap)`** ```java String sql = "insert into student(name,age,gender) values(:name,:age,:gender) "; Map<String, Object> params = new HashMap<>(16); params.put("name", "张三"); params.put("age", 25); params.put("gender", "男"); int rows = jdbcTemplate.update(sql, params); ``` **2.`int update(String sql, SqlParameterSource paramSource)`** ```java String sql = "insert into student(name,age,gender) values(:name,:age,:gender) "; //实体类的属性名是name,age,gender Student student = new Student("李四", 25, "男"); int rows = jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(student)); ``` **3. 获取自增的主键** `int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder)` ```java String sql = "insert into student(name,age,gender) values(:name,:age,:gender) "; KeyHolder keyHolder = new GeneratedKeyHolder(); Student student = new Student("李四", 25, "男"); int rows = jdbcTemplate.update(sql, new BeanPropertySqlParameterSource(student), keyHolder); //获取自增主键 int key = keyHolder.getKey().intValue(); ``` **4. 批量操作:`int[] batchUpdate(String sql, Map<String, ?>[] batchValues)`** ```java String sql = "insert into student(name,age,gender) values(:name,:age,:gender) "; Map<String, Object>[] params = new HashMap[1]; Map<String, Object> param = new HashMap<>(16); param.put("name", "王五"); param.put("age", 26); param.put("gender", "男"); params[0] = param; int[] rows = jdbcTemplate.batchUpdate(sql, params); ``` **5. 批量操作:`int[] batchUpdate(String sql, final SqlParameterSource[] batchArgs)`** ```java String sql = "insert into student(name,age,gender) values(:name,:age,:gender) "; SqlParameterSource[] params = new BeanPropertySqlParameterSource[1]; //实体类的属性名是name,age,gender SqlParameterSource param = new BeanPropertySqlParameterSource(new Student("赵六", 30, "男")); params[0] = param; int[] rows = jdbcTemplate.batchUpdate(sql, params); ```