source: http://rostislav-matl.blogspot.com/2011/08/fast-inserts-to-postgresql-with-jdbc.html

Thanks !

Fast Inserts to PostgreSQL with JDBC and COPY FROM

Labels: batchescopy frominsertsjavajdbc
I was reading some materials on how to make database inserts as efficient as possible from Java. it was motivated by an already existing application for storing of some measurements into PosgtreSQL. So I decided to compare known approaches to see if there is some way how to improve the application already using batched inserts.

For the purpose of  the test I created following table:

CREATE TABLE measurement
(
measurement_id bigint NOT NULL,
valid_ts timestamp with time zone NOT NULL,
measurement_value numeric(19,4) NOT NULL,
CONSTRAINT pk_mv_raw PRIMARY KEY (measurement_id, valid_ts)
)
WITH (OIDS=FALSE)

I decided to test the insertion of 1000 records to the table. The data for the recors was generated before running of any of test methods. Four test methods were created to reflect ususal approaches:

  • VSI (Very Stupid Inserts) - executing queries made of concatenated Strings one by one
  • SPI  (Stupid Prepared Inserts) - similar to VSI but using prepared statements
  • BPI (Batched Prepared Inserts) - prepared inserts, executed in batches of various length
  • CPI (Copy Inserts) - inserts based on COPY FROM, executed in batches of various length

Prior to each inserts the table is cleared, the same after all data are succesfully inserted. Commit is called only once in each test method, following all the insert calls.  The following code exerpts illustrate the above listed approaches:

VSI

for (int i=0; i<testSize; i++)
{
insertSQL = "insert into measurement values ("
+ measurementIds[i] +",'"+ timestamps[i] +"',"+values[i]+")";
insert.execute(insertSQL);
}

SPI

PreparedStatement insert = conn.prepareStatement("insert into measurement values (?,?,?)");
for (int i=0; i<testSize; i++)
{
insert.setLong(1,measurementIds[i]);
insert.setTimestamp(2, timestamps[i]);
insert.setBigDecimal(3, values[i]);
insert.execute();
}

BPI

PreparedStatement insert = conn.prepareStatement("insert into measurement values (?,?,?)");
for (int i=0; i<testSize; i++)
{
insert.setLong(1,measurementIds[i]);
insert.setTimestamp(2, timestamps[i]);
insert.setBigDecimal(3, values[i]);
insert.addBatch();
if (i % batchSize == 0) { insert.executeBatch(); }
}
insert.executeBatch();

CPI

StringBuilder sb = new StringBuilder();
CopyManager cpManager = ((PGConnection)conn).getCopyAPI();
PushbackReader reader = new PushbackReader( new StringReader(""), 10000 );
for (int i=0; i<testSize; i++)
{
sb.append(measurementIds[i]).append(",'")
.append(timestamps[i]).append("',")
.append(values[i]).append("\n");
if (i % batchSize == 0)
{
reader.unread( sb.toString().toCharArray() );
cpManager.copyIn("COPY measurement FROM STDIN WITH CSV", reader );
sb.delete(0,sb.length());
}
}
reader.unread( sb.toString().toCharArray() );
cpManager.copyIn("COPY measurement FROM STDIN WITH CSV", reader );

I hoped to get some improvements for using COPY FROM instead of batched inserts but not expected no big gain. But the results were a pleasant surprise. For a batch of size 50 (as defined in the original aplication I wanted to improve) the COPY FROM gave 40% improvement.  I expect some improvements when data come from a stream and skip the StringBuffer-with-PushbackReader exercise.

See the graphs yourself - the number following the method abbreviation is the size of the batch.

Average time in milliseconds
All the 200 runs individually

【转载】Fast Inserts to PostgreSQL with JDBC and COPY FROM的更多相关文章

  1. 数据库语言(三):MySQL、PostgreSQL、JDBC

    MySQL MySQL资料很多,这里只给出一个在论坛博客中最常用的操作:分页 mysql> select pname from product limit 10,20; limit的第一个参数是 ...

  2. (转载)SQL Server 2008 连接JDBC详细图文教程

    点评:SQL Server 2008是目前windows上使用最多的sql数据库,2008的安装机制是基于framework重写的,特点是非常耗时间SQL Server 2008是目前windows上 ...

  3. postgresql Java JDBC 一次性传入多个参数到 in ( ?) - multple/list parameters

    经常不清楚需要传入多少个参数到 IN () 里面,下面是简单方法: 方法 1 - in ( SELECT * FROM unnest(?)) ) Integer[] ids={1,2,3};      ...

  4. 【转载】C#的DataTable类Clone及Copy方法的区别

    在C#中的Datatable类中,Clone方法和Copy方法都可以用来复制当前的DataTable对象,但DataTable类中的Clone方法和Copy方法还是有区别的,Clone方法只复制结构信 ...

  5. PostgreSQL数据导出导入COPY

    [postgres@DELL-R720 bin]$ ./psql -p 6432psql (9.4.5)Type "help" for help. postgres=# postg ...

  6. 编写postgresql函数执行循环copy命令导入大数据

    CREATE OR REPLACE FUNCTION copyData() RETURNS boolean AS $BODY$ DECLARE i int; begin i :=1; FOR i IN ...

  7. JMeter学习(八)JDBC测试计划-连接Oracle(转载)

    转载自 http://www.cnblogs.com/yangxia-test 一.测试环境准备   Oracle:10g  JDBC驱动:classes12.jar oracle安装目录下(orac ...

  8. 数据库jdbc链接:mysql, oracle, postgresql

    #db mysql#jdbc.driver=com.mysql.jdbc.Driver#jdbc.url=jdbc:mysql://localhost:3306/mysql?&useUnico ...

  9. PostgreSQL相关的软件,库,工具和资源集合

    PostgreSQL相关的软件,库,工具和资源集合. 备份 wal-e - Simple Continuous Archiving for Postgres to S3, Azure, or Swif ...

随机推荐

  1. [专题汇总]AC自动机

    1.The 2011 ACM-ICPC Asia Dalian Regional Contest ZOJ 3545 Rescue the Rabbit  简单的AC自动机+状压DP, 状态DP[nod ...

  2. java学习第十一天

    第十二次课 目标 一维数组(创建访问) 一.概念与特点 1.概念 相同数据类型的有序集合[] 数组名: 容器的名字 元素:  下标变量,数组名[下标] 长度:  length 下标:   位置.索引  ...

  3. git error

    一,今天在上传代码时出错: $ git push -u origin mastererror: The requested URL returned error: 403 Forbidden whil ...

  4. Selenium定位二 --多个元素定位方法 和层级定位方法

    定位多个元素: findElements()方法可以返回一个符合条件的元素List 组 如: public void hitUpdatePersonnel(WebDriver driver, int ...

  5. 我用工具怎么连接不上mysql数据库的? MySql access denied for user错误

    MySql access denied for user错误 方法/步骤   MySql远程连接时的"access denied for user **@**"错误,搞的我很头大, ...

  6. JQUERY知识总结

    1, 让页面上某一个已存在的SELECT被选中的JQuery写法  $("#test").find("option[value='3']").prop(&quo ...

  7. Python字典实现三级菜单

    ################################################ # Task Name: 三级菜单 # # Description:打印省.市.县三级菜单 # # 可 ...

  8. ASP.NET MVC+EF框架+EasyUI实现权限管理系列

    http://www.cnblogs.com/hanyinglong/archive/2013/03/22/2976478.html ASP.NET MVC+EF框架+EasyUI实现权限管理系列之开 ...

  9. 如何解决虚拟机克隆导致"Bringing up interface eth0: Error: No suitable device found: no device found for connection 'System eth0'."

    在VMware的虚拟机中克隆CentOS,在重启网卡的时候报错: Bringing up interface eth0:  Error: No suitable device found: no de ...

  10. SQL Server 2012将数据库备份到网络中的共享文件夹

    把计算机computer1 中的数据库备份到计算机computer2(IP:192.168.0.130)中的一个共享文件夹下 在computer2中的F盘下建一个共享文件夹叫DBBackupShare ...