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

我需要从一个数据库中取一个表并将其上传到另一个数据库.
所以,我创建了两个单独的连接.这是我的代码
Connection connection1 = // set up connection to dbms1
Statement statement = connection1.createStatement();
ResultSet result = statement.executeQuery("select * from ............. "); 

Connection connection2 =  // set up connection to dbms2
// Now I want to upload the ResultSet result into the second database
Statement statement2 = connection2.createStatement("insert into table2 " + result);
statement2.executeUpdate();

上面的最后一行不起作用
我怎样才能做到这一点 ?底线是如何重用ready结果集

ResultSet是一个现成的java对象.我希望有一种方法可以将它添加到批处理或类似的东西和executeUpdate,但不能将结果集写入某个临时空间(List,csv等)和插入

解决方法

最简单的方法是插入一个 prepared statement.它允许您创建单个语句对象,该对象可用于使用不同的参数值多次运行查询.
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中,因此无需存储整个结果集.

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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...