我正在使用 Postgres sql 数据库。我需要针对database-A
我从该查询中获得的任何结果运行 SQL 查询,我需要将结果database-B
按原样插入,这必须在每周周五进行。
所以我决定使用ScheduledExecutorService
which 将在周五每周调用一个特定的方法来完成上述工作。
以下是我(getFromDatabase)
每周五运行的方法 -
在下面的方法中,我正在执行一个简单的选择查询,database-A
并将结果存储在TestResponse
方法中
protected static void getFromDatabase() {
TestResponse response = null;
TestDaoImpl dao = new TestDaoImpl();
String sql1 = "select col1, col2 from application limit 5";
try {
// get the data from database-A table
response = dao.getFromDatabaseA(sql1);
System.out.println(response);
// now iterate this response and then insert into database-B table
insertIntoDatabase(response);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void insertIntoDatabase(TestResponse resp) {
// how to use resp so that I can generate below correct insert SQL query?
// which I can use to execute it?
String query = "INSERT into table-database-B .... ";
}
以下是我的getFromDatabaseA
方法 -
private List<String> col1List = new LinkedList<String>();
private List<String> col2List = new LinkedList<String>();
public TestResponse getFromDatabaseA(String query) throws Exception {
TestResponse response = new TopMalwareAppsResponse();
try {
conn = TestConnection.getInstance().getCpds().getConnection();
statement = conn.createStatement();
rs = statement.executeQuery(query);
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
String col1 = rs.getString("col1");
col1List.add(col1);
String col2 = rs.getString("col2");
col2List.add(col2);
}
response.setCol1(col1List);
response.setCol2(col2List);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
下面是我的TestResponse
类,其中的所有值都col1
将进入col1
链表,所有的值都col2
将进入col2
链表。
public class TestResponse {
private List<String> col1;
private List<String> col2;
// getters and setters
}
现在我不确定如何以这种方式迭代TestResponse
方法insertIntoDatabase
,以便能够进行正确的 SQL 查询。然后我可以按原样使用这个 SQL 查询来插入。