且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将表从一个数据库复制到另一个数据库?

更新时间:2021-12-26 22:09:27

最简单的方法是使用

The simplest way to do this is with a prepared statement for the insert. It lets you create a single statement object that can be used to run the query multiple times with different parameter values.

try (final Statement statement1 = connection1.createStatement();
     final PreparedStatement insertStatement = 
     connection2.prepareStatement("insert into table2 values(?, ?)"))
{
    try (final ResultSet resultSet =
         statement1.executeQuery("select foo, bar from table1"))
    {
        while (resultSet.next())
        {
            // Get the values from the table1 record
            final String foo = resultSet.getString("foo");
            final int bar = resultSet.getInt("bar");

            // Insert a row with these values into table2
            insertStatement.clearParameters();
            insertStatement.setString(1, foo);
            insertStatement.setInt(2, bar);
            insertStatement.executeUpdate();
        }
    }
}

当您遍历 table1 的结果时,行将插入到 table2 中,因此无需存储整个结果集.

The rows are inserted into table2 as you iterate through the results from table1, so there's no need to store the whole result set.

您还可以使用准备好的语句的 addBatch() executeBatch()方法来排队所有插入并将它们一次性发送到数据库,而不是一次为每个插入的单独行向数据库发送一条单独的消息.但这迫使JDBC在本地将所有挂起的插入保留在内存中,这似乎是您在尝试避免.因此,在这种情况下,***一次插入一次.

You can also use the prepared statement's addBatch() and executeBatch() methods to queue up all the inserts and send them to the database all at once, instead of sending a separate message to the database for each individual inserted row. But that forces JDBC to hold all the pending inserts in memory locally, which it seems you're trying to avoid. So the one-row-at-a-time inserts are your best bet in this case.