File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Groovy and the fly likes Calling a psql command from a Groovy script Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "Calling a psql command from a Groovy script" Watch "Calling a psql command from a Groovy script" New topic

Calling a psql command from a Groovy script

Anya Agarwal

Joined: Mar 04, 2012
Posts: 1

I am writing a groovy script ( version 1.8.5) which needs to copy data from a file into a table ( Postgres Database). I could use the SQL command COPY, but that requires the script to run as superuser ( which is not an option I can use). The other alternative is to use \COPY, which is a psql command. But psql is a command line tool for PostgresSQL. Is there a way to call \COPY from within the Groovy script?

I tried the following:

What I am trying to do in the above code is log onto to the psql command line and then run the \COPY command, but I get the following error:

Just wondering if it is possible to call \COPY from a script? If not, is there any other way I can bulk copy the data from the file to the table? Its a huge file, and copying row by row will be very inefficient.

Thanks so much in advance for all your help.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3152

that is not the right way to interact with the database. You need to use JDBC. For more details read the documentation here

Mohamed Sanaulla | My Blog
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

The problem you're having is that you're trying to execute a command which waits for input from the user. The way your code is written, it won't interact with the running process. I did some googling and found out that what you are trying to do is rather tricky because of not knowing if the running program (psql) is ready for input or not.

I'm sorry that I don't have a "how to" answer but at least this might get you started in the right direction of what to search for to find a solution.

GenRocket - Experts at Building Test Data
I agree. Here's the link:
subject: Calling a psql command from a Groovy script
It's not a secret anymore!