spring-boot JdbcTemplate增刪改查筆記
阿新 • • 發佈:2018-11-10
spring-boot增刪改查筆記
1. 查詢操作
//列表查詢
List<Map<string, Object>> results = jdbctemplate.query("select * from tableName")
// 查詢數量
jdbcTemplate.queryForInt("select count(0) from tableName");
//查詢自增id
String sql = "show table status where Name = 'tableName'";
Map<String, Object> queryData = jdbcTemplate.queryForMap(sql);
2. 修改操作
sql: update tableName set param = "1" WHERE id = 25
jdbcTemplate.update(sql)
3. 新增操作
jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)",
new Object[]{user.getUsername(),user.getPassword()});
4. 刪除操作
jdbcTemplate.update(
"delete from tb_test1 where id = ?" ,
new Object[]{user.getId()},
new int[]{java.sql.Types.INTEGER});
5. 批量插入,並返回插入數量
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
String sql = "update tableName set param = '1' WHERE id = 25"
int[] updateCounts = jdbcTemplate.batchUpdate(sqlStr, new BatchPreparedStatementSetter() {
@Override
public int getBatchSize() {
return data.size();
}
@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
DataObject dataItem = data.get(i);
ps.setString(1, dataItem.getTitle());
ps.setInt(2, dataItem.getRepo_id());
ps.setString(3, dataItem.getType());
ps.setString(4, dataItem.getParams());
}
});
return updateCounts.length;
參考連結
1. Spring中jdbcTemplate的用法例項(一)
2. SQL 多條件查詢
持續更新中…