用Java查询数据库后返回一个数组 [英] Return an array after querying database in Java
问题描述
我必须查询MSSQL数据库,并且希望将查询结果作为Array或ArrayList返回.
I have to query a MSSQL database and I want the result of the query to returned as a Array or ArrayList.
我现在有一个这段代码,但是它给出了一个错误. 我已经连接到数据库,所以这不是问题.
I have a this code now, but it gives an error. I have a connection to the database so that's not the problem.
public ArrayList<Array> queryResult(String q) throws SQLException {
ArrayList<Array> array = new ArrayList<>();
Statement statement = this.getConnection().createStatement();
ResultSet rs = statement.executeQuery(q);
while(rs.next()) {
Array n = rs.getArray(rs.getRow());
System.out.println(n);
array.add(n);
}
return array;
}
我收到以下错误
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: This operation is not supported.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.NotImplemented(SQLServerResultSet.java:750)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getArray(SQLServerResultSet.java:2625)
at server.Database.queryResult(Database.java:52)
at server.Server.listen(Server.java:57)
at server.Server.run(Server.java:34) at
server.Server.<init>(Server.java:28) at
server.Server.main(Server.java:94) Java Result: 1
推荐答案
getArray()
将当前行的特定列的值作为数组返回.看到此内容- http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getArray%28int%29
getArray()
returns the value of a particular column of the current row as an array. See this - http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getArray%28int%29
如果要将行值作为数组获取,则必须为诸如此类的事情编写代码.
If you want to get row values as array then you have to write code for that some thing like this.
while (rs.next()){
java.util.ArrayList alRowData = new java.util.ArrayList();
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
for(int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex ++){
alRowData.add(rs.getObject(columnIndex));
}
System.out.println(alRowData);
}
这篇关于用Java查询数据库后返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!