推荐使用jdbcTemplate
使用这个,不用手动关闭Statement Connection,很方便。
@Service("vTService")
public class VTServiceImpl{
@Autowired
@Qualifier("jdbcTemplate2") //有多个数据源的,需要名称区分
private JdbcTemplate jdbcTemplate;
public String createTable(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);
# 结果集,类似ResultSet
SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
while(sqlRowSet.next){
long id = sqlRowSet.getLong(1)
}
映射自定义类
RowMapper<User> rowMapper=new BeanPropertyRowMapper<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);
}