Spring获取当前数据库指定表的信息
2020-03-24 本文已影响0人
EasyNetCN
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("tables")
public class TableServiceController {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@GetMapping("{table}/columns")
public Flux<Map<String, Object>> columns(@PathVariable("table") String table) {
var paramSource = new HashMap<String, Object>(2);
paramSource.put("db", getDb());
paramSource.put("table", table);
return Flux.fromIterable(namedParameterJdbcTemplate.queryForList(
"SELECT * FROM information_schema.columns WHERE table_schema = :db AND table_name = :table ORDER BY ordinal_position ASC",
paramSource));
}
public String getDb() {
return namedParameterJdbcTemplate.getJdbcTemplate().queryForObject("SELECT DATABASE()", String.class);
}
}