如何存储 1000 行以及之后执行批处理?

How to store 1000 lines and after to execute the batch?

我正在尝试向数据库中插入大量数据(几百万行),我想使用 "batches" 来完成。所以,我有一个方法,它从一个 csv 中接收 1000 行,它会在 for 循环遍历所有这 100 万行之后执行批处理,依此类推。我写了这个方法,但它似乎只从那 1000 行中添加到数据库中。

这是我试过的方法。

public void insertToDatabase(List<Account> listOfAccounts, Connection connection){

    PreparedStatement preparedStatement = null;
    try
    {
        preparedStatement = connection.prepareStatement( INSERT_ACCOUNT_QUERY );
    }
    catch( SQLException e1 )
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try
    {

        for( Account account : listOfAccounts )
        {

            connection.setAutoCommit( false );


            preparedStatement.setString( 1, account.getFirstName( ) );
            preparedStatement.setString( 2, account.getLastName( ) );
            preparedStatement.setInt( 3, account.getHomeTellNumber( ) );
            preparedStatement.setInt( 4, account.getMobileTellNumber( ) );
            preparedStatement.setString( 5, account.getAddress( ) );
            preparedStatement.setString( 6, account.getCity( ) );
            preparedStatement.setString( 7, account.getState( ) );
            preparedStatement.setString( 8, account.getJob( ).getCode( ) );
            preparedStatement.setString( 9, account.getLocale( ).getCode( ) );

            preparedStatement.addBatch( );
        }


        preparedStatement.executeBatch( );

    }

    catch( SQLException e )
    {
        // TODO Auto-generated catch block
        e.printStackTrace( );
    }
    finally
    {
        try
        {
            preparedStatement.close( );
        }
        catch( SQLException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace( );
        }
    }
}

因此,该方法仅将列表中的最后一个元素插入数据库,而不是在末尾一次添加所有元素。

谢谢。

如果您启用自动提交,您当前的脚本应该可以正常工作。由于您已将自动提交设置为 false,因此您必须明确提交更新:

preparedStatement.executeBatch();
// add the next line
connection.commit();

我建议只启用自动提交。如果您怀疑您的 JDBC 驱动程序在默认情况下确实有此设置,那么在您进入循环之前只需调用以下一次:

connection.setAutoCommit(true);

然后,您将不必明确提交您的工作。