Java Springboot项目执行sql的方式

2022-08-19 10:06:44

推荐使用jdbcTemplate

使用这个,不用手动关闭Statement Connection,很方便。

@Service("vTService")publicclassVTServiceImpl{@Autowired@Qualifier("jdbcTemplate2")//有多个数据源的,需要名称区分privateJdbcTemplate jdbcTemplate;publicStringcreateTable(String id){String tableName="tmp"+ id;String sql="CREATE TABLE \"public\".\""+ tableName+"\" (c integer, a integer, b integer, d bytea);"+"CREATE UNIQUE INDEX \""+ tableName+"_unique_zcr_idx\" on \"public\".\""+ tableName+"\" (c, a, b);";
        jdbcTemplate.execute(sql);return tableName;}}

需要结果的

# 单个结果Long id= jdbcTemplate.executeForObject("select id from tb where xxx = 'yyy'",Long.class);
# 多个结果String sql="select id from tb";List<Long> ids= jdbcTemplate.executeForList(sql,Long.class);
# 结果集,类似ResultSetSqlRowSet sqlRowSet= jdbcTemplate.queryForRowSet(sql);while(sqlRowSet.next){long id= sqlRowSet.getLong(1)}

映射自定义类

RowMapper<User> rowMapper=newBeanPropertyRowMapper<User>(User.class);String sql="select userName,userPwd from userinfo";List<User> users=jt.query(sql,rowMapper);for(User u:users){System.out.println(u);}
  • 作者:BIG*BOSS
  • 原文链接:https://blog.csdn.net/qq_42158942/article/details/118905628
    更新时间:2022-08-19 10:06:44