我正在使用Postgres sql数据库..我需要针对database-A
运行SQL查询以及从该查询得到的任何结果,我需要将结果插入database-B
,因为它是这必须每周五每周一次。
所以我决定使用ScheduledExecutorService
,它将在星期五每周调用一个特定的方法来完成上述工作。
以下是我的方法(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查询来插入。
答案 0 :(得分:1)
您将列详细信息列入对象,这不是一个好的行为,
将其更改为
public class TestResponse {
private String col1;
private String col2;
// getters and setters
}
使用
List<TestResponse> responses = null;
使用
private static void insertIntoDatabase(List<TestResponse> resps) {
// how to use resp so that I can generate below correct insert SQL query?
// which I can use to execute it?
**// Iterate the above list and update second table**
String query = "INSERT into table-database-B .... ";
}
改变
getFromDatabaseA
像这样
List<TestResponse> testResponses = new ArrayList<TestResponse>();
// Iterate for values or execute query for multiple time to get all details from table 1
{
TestResponse testResponse = new TestResponse();
testResponse.setsetCol1(/* ADD COL1 DATA */);
testResponse.setsetCol2(/* ADD COL2 DATA */);
testResponses.add(testResponse);
}
return testResponses;
答案 1 :(得分:-1)
SELECT * FROM old_table INTO new_table
或者您可以使用
insert into table2 values(select * FROM table1);