代码下载:https://files.cnblogs.com/files/xiandedanteng/fastfilltable20191222.rar

表testtb18的结构如下:

CREATE TABLE testtb18
(
    id NUMBER not null primary key,
    name NVARCHAR2() not null,
    createtime ) not null
)

三个字段,正好是常用的number,nvarcha2,timestamp类型。

用java程序创建这表表的代码如下:

/**
 * 数据库连接参数
 * @author 逆火
 *
 * 2019年11月16日 上午8:09:24
 */
public final class DBParam {
    public final static String Driver = "oracle.jdbc.driver.OracleDriver";
    ::orcl";
    public final static String User = "ufo";
    ";
}
package com.hy.fastfilltable;

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

import org.apache.log4j.Logger;

// Used to create a table in oracle
public class TableCreater {
    private static Logger log = Logger.getLogger(TableCreater.class);
    private final String table="testtb18";

    public boolean createTable() {
        Connection conn = null;
        Statement stmt = null;

        try{
            Class.forName(DBParam.Driver).newInstance();
            conn = DriverManager.getConnection(DBParam.DbUrl, DBParam.User, DBParam.Pswd);
            stmt = conn.createStatement();

            String createTableSql=getCreateTbSql(table);
            stmt.execute(createTableSql);

            if(isTableExist(table,stmt)==true) {
                log.info("Table:'"+table+"' created.");
                return true;
            }

        } 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());
            }
        }

        return false;
    }

    /**
     * Get a table's ddl
     * @param table
     * @return
     */
    private String getCreateTbSql(String table) {
        StringBuilder sb=new StringBuilder();
        sb.append("CREATE TABLE "+table);
        sb.append("(");
        sb.append("id NUMBER not null primary key,");
        sb.append("name NVARCHAR2(60) not null,");
        sb.append("createtime TIMESTAMP (6) not null");
        sb.append(")");

        return sb.toString();
    }

    // Execute a sql
    //private int executeSql(String sql,Statement stmt) throws SQLException {
    //    return stmt.executeUpdate(sql);
    //}

    // If a table exists
    private boolean isTableExist(String table,Statement stmt) throws SQLException {
        String sql="SELECT COUNT (*) as cnt FROM ALL_TABLES WHERE table_name = UPPER('"+table+"')";

        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {
            int count = rs.getInt("cnt");
            return count==1;
        }

        return false;
    }

    // Entry point
    public static void main(String[] args) {
        TableCreater tc=new TableCreater();
        tc.createTable();
    }
}

现在我想就往这张表里添值,到一百万条记录,可以这么做:

package com.hy.fastfilltable;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;

import org.apache.log4j.Logger;

import com.hy.DBParam;

public class FastTableFiller {
    private static Logger log = Logger.getLogger(FastTableFiller.class);

    private final String Table="testtb18";
    private final int Total=1000000;

    public boolean fillTable() {
        Connection conn = null;
        Statement stmt = null;

        try{
            Class.forName(DBParam.Driver).newInstance();
            conn = DriverManager.getConnection(DBParam.DbUrl, DBParam.User, DBParam.Pswd);
            conn.setAutoCommit(false);
            stmt = conn.createStatement();

            long startMs = System.currentTimeMillis();
            clearTable(stmt,conn);
            fillDataInTable(stmt,conn);

            long endMs = System.currentTimeMillis();
            log.info("It takes "+ms2DHMS(startMs,endMs)+" to fill "+toEastNumFormat(Total)+" records to table:'"+Table+"'.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.print("Can't close stmt/conn because of " + e.getMessage());
            }
        }

        return false;
    }

    private void clearTable(Statement stmt,Connection conn) throws SQLException {
        stmt.executeUpdate("truncate table "+Table);
        conn.commit();
        log.info("Cleared table:'"+Table+"'.");
    }

    private void fillDataInTable(Statement stmt,Connection conn) throws SQLException {
        StringBuilder sb=new StringBuilder();
        sb.append(" Insert into "+Table);
        sb.append(" select rownum,dbms_random.string('*',50),sysdate from dual ");
        sb.append(" connect by level<="+Total);
        sb.append(" order by dbms_random.random");

        String sql=sb.toString();
        stmt.executeUpdate(sql);
        conn.commit();

    }

    // 将整数在万分位以逗号分隔表示
    public static String toEastNumFormat(long number) {
        DecimalFormat df = new DecimalFormat("#,####");
        return df.format(number);
    }

    // change seconds to DayHourMinuteSecond format
    private static String ms2DHMS(long startMs, long endMs) {
        String retval = null;
        long secondCount = (endMs - startMs) / 1000;
        String ms = (endMs - startMs) % 1000 + "ms";

        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;

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

        return retval + ms;
    }

    // Entry point
    public static void main(String[] args) {
        FastTableFiller f=new FastTableFiller();
        f.fillTable();
    }
}

执行效果还不错:

2019-12-22 15:21:02,412 INFO[main]-Cleared table:'testtb18'.
2019-12-22 15:22:28,669 INFO[main]-It takes 1m26s268ms to fill 100,0000 records to table:'testtb18'.

注意:插一千万数据就会报oom异常,怎么解决请大家自行考虑,我暂时没这样的需求。

再看看表中情况;

--END-- 2019年12月22日15:35:27

【java/oralce/sql】往一张仅有id,名称,创建时间三个字段的表中插入百万数据需要多久?1分26秒的更多相关文章

  1. 【Oracle/Java】向三张表各插入百万数据,共用时18分3秒,平均每张表6分钟

    三张表DDL如下: CREATE TABLE tb01 ( "ID" ,) not null primary key, "NAME" NVARCHAR2() n ...

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

    由于按一千条一插程序长期无反应,之后改为百条一插方式,运行完发现插入百万记录需要9m17s,虽然比MySQL效率差,但比单条插入已经好不少了. 对Oracle的批量插入语法不明的请参考:https:/ ...

  3. EF Core中,通过实体类向SQL Server数据库表中插入数据后,实体对象是如何得到数据库表中的默认值的

    我们使用EF Core的实体类向SQL Server数据库表中插入数据后,如果数据库表中有自增列或默认值列,那么EF Core的实体对象也会返回插入到数据库表中的默认值. 下面我们通过例子来展示,EF ...

  4. sql 所有数据表中 插入字段

    declare @tablename varchar(200)declare @sql varchar(2000)declare cur_t cursor forselect name from sy ...

  5. SQL Server批量向表中插入多行数据语句

    因自己学习测试需要,需要两个有大量不重复行的表,表中行数越多越好.手动编写SQL语句,通过循环,批量向表中插入数据,考虑到避免一致问题,设置奇偶行不同.个人水平有限,如有错误,还望指正. 语句如下: ...

  6. MySQL_(Java)使用JDBC向数据库中插入(insert)数据

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...

  7. SQL 在表中插入

    SQL INSERT INTO 语句(在表中插入) INSERT INTO 语句用于向表中插入新记录. SQL INSERT INTO 语句 INSERT INTO 语句用于向表中插入新记录. SQL ...

  8. SQL语句 在一个表中插入新字段

    SQL语句 在一个表中插入新字段: alter table 表名 add 字段名 字段类型 例: alter table OpenCourses add Audio varchar(50)alter ...

  9. SQL语句更新时间字段的年份、月份、天数、时、分、秒

    SQL语句更新时间字段的年份.月份.天数.时.分.秒 --修改d表日期字段的年份update dset birth=STUFF(convert(nvarchar(23),birth,120),1,4, ...

随机推荐

  1. Weshop基于Spring Cloud开发的小程序商城系统

    WESHOP | 基于微服务的小程序商城系统 Weshop是基于Spring Cloud(Greenwich)开发的小程序商城系统,提供整套公共微服务服务模块,包含用户中心.商品中心.订单中心.营销中 ...

  2. X509证书信任管理器类的详解

    在JSSE中,证书信任管理器类就是实现了接口X509TrustManager的类.我们可以自己实现该接口,让它信任我们指定的证书. 接口X509TrustManager有下述三个公有的方法需要我们实现 ...

  3. rsync异常处理

    实验环境: centos7.6 实验目的:    错误的思考,在目标端执行rsync拉取源端文件,源端也必须存在rsync命令,目的用于差异比对实现增量传输! 01.执行rsync命令不存在 02.执 ...

  4. PHP实现Redis单据锁,防止并发重复写入

    一.写在前面 在整个供应链系统中,会有很多种单据(采购单.入库单.到货单.运单等等),在涉及写单据数据的接口时(增删改操作),即使前端做了相关限制,还是有可能因为网络或异常操作产生并发重复调用的情况, ...

  5. python生成测试报告HTMLTestRunner时报错ValueError: write to closed file的解决办法

    使用HTMLTestRunner时出现了以下问题: self.stream.write(output.encode('utf8')) ValueError: write to closed file ...

  6. Beta产品测试报告:那周余嘉熊掌将得队、为了交项目干杯队

    测试对象: 那周余嘉熊掌将得队 一.截图 安装截图 运行截图 二.测试情况 1.第一次上手体验感觉如何?能否正常运行? 界面UI设计令人眼前一亮,客户端和管理员端皆可正常运行.组件动画流畅,响应流畅, ...

  7. oracle之随机数

    一.首先创建一个测试表 select * from DIM_IA_TEST1 生成随机数 select t.*,rownum rn from  (select * from DIM_IA_TEST1 ...

  8. PLSQL 美化规则文件详解

    PL/SQL中有个代码优化的功能,里面可以定义规则,挺好用的,跟大家分享下: 1.首先新建一个my.br文件,在文件中复制以下内容 Version=1 RightMargin=90 Indent=4 ...

  9. python基础语法8 叠加装饰器,有参装饰器,wraps补充,迭代器

    叠加装饰器: 叠加装饰器 - 每一个新的功能都应该写一个新的装饰器 - 否则会导致,代码冗余,结构不清晰,可扩展性差 在同一个被装饰对象中,添加多个装饰器,并执行. @装饰1 @装饰2 @装饰3 de ...

  10. jsbridge与通信模型

    三层通信模型: 应用层.解释层.会话层: 通信协议: 通信原语: 报文格式: 网络层: _evaluateJavascript 会话层: #define kQueueHasMessage   @&qu ...