0

我有一张类似这样的地图-

ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableList

这将有这样的数据-

示例示例-

{table1={DRIVER=oracle.jdbc.driver.OracleDriver, PASSWORD=stage_cs_user, URL=jdbc_url, SUFFIX=xt1, SQL=sql, USER=user}, table2={DRIVER=driver_name, PASSWORD=pass, URL=jdbc_url2, SUFFIX=xt2, SQL=sql2, USER=user}}

我正在尝试遍历上面的地图-

class Task implements Runnable {

private Connection[] dbConnection = null;
private final ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableLists;

public Task(ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableNames) {
    this.tableLists = tableNames;
}

@Override
public void run() {

for (int i = 0; i < tableLists.size(); i++) {

dbConnection[i] = getDBConnection(tableLists.get(i).get("URL"), tableLists.get(i).get("USERNAME"), tableLists.get(i).get("PASSWORD"), tableLists.get(i).get("DRIVER"));
    }
  }
}

它给了我Null Pointer Exceptionget call. 我在这里有什么遗漏吗?如果是,我该如何解决?因为我需要dbConnection根据大小分配 0 和 1 tableLists

更新代码:-

做出这样的改变后——

private Connection[] dbConnection = null;


        int j=0;
        for (Map<String, String> map : tableLists.values()) {

            dbConnection[j] = getDBConnection(map.get("URL"), map.get("USER"), map.get("PASSWORD"), map.get("DRIVER"));
            callableStatement[j] = dbConnection[j].prepareCall(map.get("SQL"));

            methods[j] = getRequiredMethods(map.get("SUFFIX"));
            j++;
        }

private Connection getDBConnection(String url, String username, String password, String driver) {

    Connection dbConnection = null;

    try {
        Class.forName(driver);
        dbConnection = DriverManager.getConnection(url, username, password);
    }

    return dbConnection;
}

它再次抛出 NPE,但这一次它在建立连接并返回时立即抛出。我在这里做错了什么?

4

2 回答 2

1

Map接口有一个Key,而不是一个索引。要获取所有条目,请尝试

int i=0;
dbConnection = new DbConnection[tableLists.size()];
for (Map<String, String> map : tableLists.values()) {
  dbConnection[i] = getDBConnection(
    map.get("URL"), 
    map.get("USER"), 
    map.get("PASSWORD"), 
    map.get("DRIVER"));
  i++;
}
于 2013-02-13T00:42:30.650 回答
0

你不应该得到像

tableLists.get(0);
tableLists.get(1);

由于 Map 不是基于索引的集合,它是基于键的。你应该得到像

tableLists.get("table1");
tableLists.get("table2");

因为您的键是“table1”和“table2”,而不是 0 和 1。

编辑: 所以你可以修改你的来源如下。

int i = 0;
for (String mapkey : tableLists.keySet()) {
    dbConnection[i] = getDBConnection(
            tableLists.get(mapkey).get("URL"), 
            tableLists.get(mapkey).get("USERNAME"),
            tableLists.get(mapkey).get("PASSWORD"),
            tableLists.get(mapkey).get("DRIVER"));
    i++;
}
于 2013-02-13T00:41:20.110 回答