【Oracle/Java】以Insert ALL方式向表中插入百万条记录,耗时9分17秒

摘要:
由于根据1000个节目很长一段时间没有回应,后来改为100个节目。运行后发现,插入数百万条记录需要9毫秒。虽然它的效率不如MySQL,但它并不亚于单个程序。

由于按一千条一插程序长期无反应,之后改为百条一插方式,运行完发现插入百万记录需要9m17s,虽然比MySQL效率差,但比单条插入已经好不少了。

对Oracle的批量插入语法不明的请参考:https://www.cnblogs.com/xiandedanteng/p/11806720.html

代码如下:

package com.hy;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;

/**
 * 百万数据插入Oracle表中
 * @author horn1
 *
 */
public class MillionInserter {
    
    // 连接到数据库的四大属性
    private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DBURL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
    private static final String USER = "system";
    private static final String PSWD = "XXXX";
    
    public void batchInsert(int count) {
        Connection conn = null;
        Statement stmt = null;
        
        try{
            long startTime = System.currentTimeMillis();
            
            Class.forName(DRIVER).newInstance();
            conn = DriverManager.getConnection(DBURL, USER, PSWD);
            stmt = conn.createStatement();
            
            int BatchSize=100;
            int index=0;
            int times=count/BatchSize;
            for(int i=0;i<times;i++) {
                StringBuilder sb=new StringBuilder();
                sb.append("INSERT ALL ");
                
                for(int j=0;j<BatchSize;j++) {
                    index=i*BatchSize+j;
                    String name="M"+index;
                    int age=j % 100;
                    
                    String raw=" INTO firsttb(NAME, age,createdtime) values(''{0}'',''{1}'',sysdate) ";
                    Object[] arr={name,age};
                    String particialSql=MessageFormat.format(raw, arr);
                    sb.append(particialSql);
                }
                
                sb.append("select * from dual");
                String sql = sb.toString();
                stmt.executeUpdate(sql);
                System.out.println("#"+i+" "+BatchSize+" records inserted");
            }
            
            long endTime = System.currentTimeMillis();
            System.out.println("Time elapsed:" + sec2DHMS((endTime - startTime)/1000) );
            
            String sql = "select count(*) as cnt from firsttb";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                String cnt = rs.getString("cnt");
                System.out.println("当前记录数:"+cnt);
            }            
            
        } catch (Exception e) {
            System.out.print(e.getMessage());
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.print("Can't close stmt/conn because of " + e.getMessage());
            }
        }
    }
    
    /**
         * 将秒转化为日时分秒
     * @param secondCount
     * @return
     */
    private static String sec2DHMS(long secondCount) {
        String retval = null;

        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;
        
        String strSeconds="";
        if(seconds!=0) {
            strSeconds=seconds + "s";
        }

        if (days > 0) {
            retval = days + "d" + hours + "h" + minutes + "m" + strSeconds;
        } else if (hours > 0) {
            retval = hours + "h" + minutes + "m" + strSeconds;
        } else if (minutes > 0) {
            retval = minutes + "m" + strSeconds;
        } else {
            retval = strSeconds;
        }

        return retval;
    }
    
    /**
     * 执行点
     * @param args
     */
    public static void main(String[] args) {
        MillionInserter mi=new MillionInserter();
        mi.batchInsert(1000000);
    }
}

输出:

#9987 100 records inserted
#9988 100 records inserted
#9989 100 records inserted
#9990 100 records inserted
#9991 100 records inserted
#9992 100 records inserted
#9993 100 records inserted
#9994 100 records inserted
#9995 100 records inserted
#9996 100 records inserted
#9997 100 records inserted
#9998 100 records inserted
#9999 100 records inserted
Time elapsed:9m17s
当前记录数:1000000

【Oracle/Java】以Insert ALL方式向表中插入百万条记录,耗时9分17秒第1张

到此真正掌握了Oracle的Insert ALL语法,并确认了其真实效率,今天又取得了一个小小的突破,重走长征路又迈出了小小却坚实的一步。

表的表结构请见:https://www.cnblogs.com/xiandedanteng/p/11691113.html

--END-- 2019年11月9日11:19:01

免责声明:文章转载自《【Oracle/Java】以Insert ALL方式向表中插入百万条记录,耗时9分17秒》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Supervisor安装与配置IIS--解决64位系统IIS网站发布出现未能加载文件或程序集“...”或它的某一个依赖项。试图加载下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

IIS连接oralce数据库时 提示“System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本”

最近由WindowsXP换到了Windows2003系统(Windows 7),Oracle也由原来的8i换到了9i。给客户发布了一个web系统,部署在本机IIS上测试的时候出现了“取不到缓存数据”的自定义异常,经过跟踪找到原因,在连接数据库时,出现“System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本...

Eclipse paho学习笔记

Eclipse Paho java 支持java和android 两个客户端异步和同步, MqttAsyncClient,MqttClient 其中 后者是前者的包装同步器,特效除了5.0都支持 有两个版本可以相互替换 <dependency> <groupId>org.eclipse.paho</...

SDP(12): MongoDB-Engine

   在akka-alpakka工具包里也提供了对MongoDB的stream-connector,能针对MongoDB数据库进行streaming操作。这个MongoDB-connector里包含了MongoSource,MongoFlow,MongoSink。我们只使用MongoSource,其它两个我们直接用mapAsyc来创造。下面是MongoSo...

利用Func封装“方法重试”功能

利用Func封装“方法重试”功能   忙余,写个利用Func封装方法重试的功能。该方法主要实现带有返回参数的方法实现多次重试,只要返回的结果不是所限定的返回值,则自动重试X次。Talk is cheap. Show me the code. /// <summary> /// 执行重试方法 /// </summary> /// &l...

SetupDi系列函数

SetupDiClassGuidsFromName WINSETUPAPI BOOL SetupDiClassGuidsFromNameA( PCSTR ClassName, LPGUID ClassGuidList, DWORD ClassGuidListSize, PDWORD RequiredSize ); SetupDiClassGuidsF...

sqlserver 中含有某字符串

查找 sqlserver 中字符串的ascii码SET TEXTSIZE 0-- Create variables for the character string and for the current -- position in the string.DECLARE @position int, @string char(8)-- Initializ...