将 Java 结果集转换为字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1685038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Java resultset to String array
提问by littleK
I am writing a program that will query an MS access database, return the query as a result set, and then I want to ultimately convert that result set into a String array, so that I can pass it into the constructor of a Swing JComboBox - so the ComboBox will list the items returned by the query.
我正在编写一个程序,该程序将查询 MS Access 数据库,将查询作为结果集返回,然后我想最终将该结果集转换为 String 数组,以便我可以将其传递给 Swing JComboBox 的构造函数 -所以 ComboBox 将列出查询返回的项目。
I have been able to store the rows of the result set into an ArrayList, and then convert that ArrayList into an object array, and the combobox will list the correct items, but as objects. I simply cannot ever cast that ArrayList to a String array. Does anyone know if this is possible? Here is some of my code...
我已经能够将结果集的行存储到一个 ArrayList 中,然后将该 ArrayList 转换为一个对象数组,组合框将列出正确的项目,但作为对象。我根本无法将该 ArrayList 转换为 String 数组。有谁知道这是否可能?这是我的一些代码...
// Convert the Resultset into an array list
public ArrayList<ArrayList<Object>> Results2Array(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<ArrayList<Object>> al = new ArrayList<ArrayList<Object>>();
while (rs.next()) {
ArrayList<Object> record = new ArrayList<Object>();
for (int i = 1; i <= columns; i++) {
Object value = rs.getObject(i);
record.add(value);
}
al.add(record);
}
return al;
}
// Convert ArrayList to Object Array, and pass into GUI
ArrayList<String> Locations = new ArrayList<String>();
ArrayList<String> Months = new ArrayList<String>();
ArrayList<String> Years = new ArrayList<String>();
try {
DB.loadDriver();
DB.makeConnection();
DB.buildStatement();
Locations = DB.getLocations();
Months = DB.getMonths();
Years = DB.getYears();
Object[] arrLocations = Locations.toArray();
Object[] arrMonths = Months.toArray();
Object[] arrYears = Years.toArray();
dbGUI ui = new dbGUI(arrLocations, arrMonths, arrYears);
ui.setVisible(true);
Can anyone offer any suggestions? Thanks!
任何人都可以提供任何建议吗?谢谢!
UPDATE:
更新:
Here is the stack trace that I am receiving:
这是我收到的堆栈跟踪:
java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.toArray(Unknown Source)
at kidsfirstdb.Main.main(Main.java:23)
采纳答案by Yishai
String[] arrLocations = locations.toArray(new String[0]);
Is the correct answer. The reason for your exception is that all the objects are in fact not strings.
是正确答案。您例外的原因是所有对象实际上都不是字符串。
You need to change this:
你需要改变这个:
Object value = rs.getObject(i);
to this:
对此:
String value = rs.getString(i);
or this:
或这个:
String value = rs.getObject(i).toString();
That last one will need a null check if you can be returning null columns.
如果您可以返回空列,最后一个将需要空检查。
Note that the toString() representation may not be exactly what you are looking for in all cases, but it will get you started.
请注意, toString() 表示可能并非在所有情况下都完全符合您的要求,但它可以帮助您入门。
Edit: If you are filling a combo box, you are going to need one column per row, no? If not, you need to represent the whole row as a string in some fashion. Then you put that in the value and put the value directly in the final array list, so your loop needs to look like this:
编辑:如果您要填充组合框,则每行需要一列,不是吗?如果没有,您需要以某种方式将整行表示为一个字符串。然后将其放入值中并将该值直接放入最终数组列表中,因此您的循环需要如下所示:
ArrayList<String> al = new ArrayList<String>();
while (rs.next()) {
ArrayList<String> record = new ArrayList<String>();
for (int i = 1; i <= columns; i++) {
String value = rs.String(i);
record.add(value);
}
String value = methodWhichConvertsArrayListToStringTheWayYouNeedItFormatted(record);
al.add(value);
}
return al;
回答by Bostone
String[] arrLocations = locations.toArray(new String[0]);
String[] arrLocations = locations.toArray(new String[0]);
The code above will convert List of Strings to String array. Now in your case you are creating List of Objects so you can't directly convert it to the String array. Generally you have 2 choices:
上面的代码将字符串列表转换为字符串数组。现在,在您的情况下,您正在创建对象列表,因此您无法将其直接转换为 String 数组。通常你有2个选择:
- Initially define your List as List of Strings and when populating the List convert your values to Strings (ether by doing Object#toString or extracting/generating meningful String value) and store that into your List, e.g. in your code do this
String value = rs.getObject(i).toString();
- If you don't do it in step 1 then you will have to allocate a String array, loop through your List, convert current value into String and stick it into array. I would go with option 1.
- 最初将您的列表定义为字符串列表,并在填充列表时将您的值转换为字符串(通过执行 Object#toString 或提取/生成字符串值)并将其存储到您的列表中,例如在您的代码中执行此操作
String value = rs.getObject(i).toString();
- 如果您没有在步骤 1 中执行此操作,则必须分配一个 String 数组,循环遍历您的 List,将当前值转换为 String 并将其粘贴到数组中。我会选择选项 1。
Just as a side note - methods in Java should start with lowercase letter
顺便提一下 - Java 中的方法应该以小写字母开头
回答by Adeel Ansari
Why not use rs.getString(). I will not recommend to do that though. But it would solve your problem. I mean just deal with String from the start. Example,
为什么不使用 rs.getString()。不过,我不建议这样做。但它会解决你的问题。我的意思是从一开始就处理 String 。例子,
// Not a good idea to pass a active resultset as a parameter.
// Use disconnected implementation instead, for example rowset.
public ArrayList<ArrayList<Object>> results2Array(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String[]> list = new ArrayList<String[]>();
while (rs.next()) {
String[] record = new String[columns];
for (int i = 1; i <= columns; i++) {
// Not a good idea to get everything as a string. This way you will
// get a default string representation of objects. Suppose, you
// want to format dates and doubles as per some requirement.
record[i-1] = rs.getString(i);
}
list.add(record);
}
return list;
}
Now you need to get it like below.
现在你需要像下面一样得到它。
String[][] arrLocations = locations.toArray(new String[locations.size()][0]);
Better still check the type and get the values appropriately, using meta-data you are having. This will help you format data, namely, dates and doubles.
最好还是使用您拥有的元数据检查类型并适当地获取值。这将帮助您格式化数据,即日期和双精度。