how to copy a data from file to PostgreSQL using JDBC?

前端 未结 2 1160
陌清茗
陌清茗 2020-11-27 18:03

I want to copy data from file to PostgreSQL DB using JDBC. I was using JDBC statement object to copy the file into DB. It is very slow.

I came to know that we can a

2条回答
  •  一整个雨季
    2020-11-27 18:34

    (based on aliasmrchips' answer:) if you have a Groovy environment (like me using it within ANT) you could do it like this (substituting the Oracle specifics with Postgres):

    // exec.groovy
    this.class.classLoader.rootLoader.addURL('${postgres-jdbc-driver-path}')
    PgScript.load()
    
    // PgScript.groovy
    // (we cannot use the org.postgres.* classes in exec.groovy already!)
    import java.io.FileReader
    import java.sql.DriverManager
    import org.postgresql.copy.CopyManager
    import org.postgresql.core.BaseConnection
    
    class PgScript {
        static void load() {        
    
            DriverManager.getConnection (
                '${jdbc-db-url}', '${db-usr}', '${db-usr-pass}'
            ).withCloseable {conn ->
                new CopyManager((BaseConnection) conn).
                    copyIn('COPY t FROM STDIN', new FileReader('${sqlfile}'))
            }
        }
    }
    

    Based also on this javaworld.com article.

提交回复
热议问题