我正在尝试使用从数据字典获取的信息创建 Oracle SQL 脚本来创建/替换多个 View 。
我已经成功地通过 JDBC 驱动程序和对数据字典的查询建立了一个工作数据库连接,它也能正常工作并返回正确的值。
但是,将查询的信息存储在 String 数组中 - 然后将其添加到 String[] 的 ArrayList 中 - 似乎出了问题,因为所有数组似乎在各自的索引位置具有相同的值,而我不这样做不知道为什么会这样。
这是我的代码,如果有人能发现错误,我将不胜感激:
public ArrayList<String[]> getDataDictionary(ArrayList<String> dbInfo, String table) throws SQLException {
ArrayList<String[]> result = new ArrayList<String[]>();
String[] resultTemp = new String[2];
... connection variables (URL, User, Pass)
... get connection, etc.
try {
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT COLUMN_NAME,DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '" + table + "'");
while (rs.next()) {
resultTemp[0] = rs.getString("COLUMN_NAME");
resultTemp[1] = rs.getString("DATA_TYPE");
// database values
System.out.println(rs.getString("COLUMN_NAME"));
System.out.println(rs.getString("DATA_TYPE"));
// array values
System.out.println(resultTemp[0]);
System.out.println(resultTemp[1]);
//The above sout's return the proper values for each pass of the loop
//This is what feels the strangest to me. The values are correct here, but when queried later they are wrong
result.add(resultTemp);
}
String[] test = new String[2];
// sout's return wrong values now, i.e. the value returned is always the same for all arrays queried in the ArrayList
//I don't understand how that can be, because the correct values were added to the ArrayList a few lines above and now they are wrong with no changes made
test = result.get(0);
System.out.println(test[0]);
System.out.println(test[1]);
test = result.get(1);
System.out.println(test[0]);
System.out.println(test[1]);
test = result.get(2);
System.out.println(test[0]);
System.out.println(test[1]);
rs.close();
statement.close();
con.close();
return result;
} catch(Exception e)
{
e.printStackTrace();
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error!");
alert.setHeaderText("Invalid SQL!");
alert.setContentText("Please verify the information you provided!");
alert.showAndWait();
return null;
}
最佳答案
您应该在循环内创建数组实例。
while (rs.next()) {
String[] resultTemp = new String[2];
resultTemp[0] = rs.getString("COLUMN_NAME");
resultTemp[1] = rs.getString("DATA_TYPE");
....
如果不这样做,会导致同一数组多次添加到结果
中。
关于java - ArrayList 中的每个 String[] 都具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28434091/