通过以下代码查询Oracle DB,并将查询结果作为JSON
返回:
Connection conn ;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:dbname";
conn = DriverManager.getConnection(url,"username","pwd");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table4 where ID = '5'");
while (rs.next()) {
String s = rs.getString("*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s);
}
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是,String s
的值始终为null。
我去过解决方案here但是从表格中选择*
无效。
答案 0 :(得分:4)
要输出JSON,您希望首先将数据累积到List<Map<String, Object>>
。
使用ResultSetMetaData
获取列数和列名。
List<Map<String, Object>> rows = new ArrayList<>();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
// Represent a row in DB. Key: Column name, Value: Column value
Map<String, Object> row = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
// Note that the index is 1-based
String colName = rsmd.getColumnName(i);
Object colVal = rsmd.getObject(i);
row.put(colName, colVal);
}
rows.add(row);
}
// Write the list of rows to output
// Recommend to use jackson-ObjectMapper to streaming json directly to outputstream:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getOutputStream(), rows);
要使用Jackson ObjectMapper,请为项目添加依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
答案 1 :(得分:2)
这里的问题不是转换为JSON(已在帖子中链接的this question中已解决),而是您调用ResultSet的方式。浏览documentation,我们可以看到getString
方法可以采用column index或column label,但不会提及*
等通配符搜索。如果您对数据库中的列一无所知,可以使用getMetadata()方法获取有关列的信息(包括列名称)。