加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 06:40:32 所属栏目:MsSql教程 来源:网络整理
导读:我需要从一个数据库中取一个表并将其上传到另一个数据库. 所以,我创建了两个单独的连接.这是我的代码 Connection connection1 = // set up connection to dbms1Statement statement = connection1.createStatement();ResultSet result = statement.executeQue
我需要从一个数据库中取一个表并将其上传到另一个数据库.
所以,我创建了两个单独的连接.这是我的代码
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在本地保存所有挂起的内存,这似乎是你试图避免的.因此,在这种情况下,一次一行插入是最好的选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读