使用map接口对象来执行查询

时间:2014-05-29 21:36:16

标签: java jdbc

在进行任何更改之前,我有以下代码:

Connection connRemote = DriverManager.getConnection("jdbc:mysql://11.11.1.111:3306/test",MainUser,MainPass);
String maindbsql = null;
maindbsql = "SELECT IP_vch FROM table1 WHERE table_dt = 1"; 
// Say for example I have following values for IP_vch 11.11.11.111,22.22.22.222,33.33.33.333
Map<String,Connection> connections = new HashMap<>();
DeviceStmt = connRemote.createStatement();
DeviceRS = DeviceStmt.executeQuery(maindbsql);
 while(DeviceRS.next()){
 try{ 
  final String ip_address = DeviceRS.getString("IP_vch");
  System.out.println("Value of IP_vch Field:"+ip_address);
  connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
  System.out.println("Connection to "+ip_address+" is successfull");
 }
 catch(SQLException ex1){
  System.out.println(" Inner While Loop Stack Trace Below:");
  ex1.printStackTrace();
 }
}//END Of DeviceRS.next() while loop 

现在,我想使用另一个SQL Query进行检查,如下所示:

loadchecksql = "SELECT COUNT(*) FROM table2";

但是,如果我们考虑以下代码(与上述略有不同):

Connection connRemote = DriverManager.getConnection("jdbc:mysql://11.11.1.111:3306/test",MainUser,MainPass);
String maindbsql = null;
maindbsql = "SELECT IP_vch FROM table1 WHERE table_dt = 1"; 
loadchecksql = "SELECT COUNT(*) FROM table2";// this table2 exists only in the IP address that are in `IP_vch` field
// Say for example I have following values for IP_vch 11.11.11.111,22.22.22.222,33.33.33.333
Map<String,Connection> connections = new HashMap<>();
DeviceStmt = connRemote.createStatement();
DeviceRS = DeviceStmt.executeQuery(maindbsql);
 while(DeviceRS.next()){
 try{ 
  final String ip_address = DeviceRS.getString("IP_vch");
  System.out.println("Value of IP_vch Field:"+ip_address);
  connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
  System.out.println("Connection to "+ip_address+" is successfull");
 }
 catch(SQLException ex1){
  System.out.println(" Inner While Loop Stack Trace Below:");
  ex1.printStackTrace();
 }
}//END Of DeviceRS.next() while loop 

但是connections是Map接口的对象,因此我想知道如何使loadchecksql工作 我将不得不执行以下操作,但我无法使用下面的connections代替connRemote

LoadCheckStmt = connRemote.createStatement();
LoadCheckRS = LoadCheckStmt.executeQuery(loadchecksql);

我想在上面的代码中将以上两行放在下一行的下面:

connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));

请告知

0 个答案:

没有答案