1

I have to make a perl script populate a database in PostgreSQL without using DBI or any sort of database interface model. I am a beginner to scripting so naturally, I'v been stuck on this for quite a while. I only have this much so far.

    open my $pipe, '|-', "psql -d postgres -U postgres", @options or die;
    # NOT SURE WHAT TO DO AFTER THIS

    close $pipe;

edit 1: Now i'm trying to do this.

 for ($count = $iters; $count >= 1; $count--) {
    $randdecimal = rand();
    $pipe "INSERT INTO random_table (runid, random_number) VALUES ($runid, $randdecimal)";
 }

but it gives me a syntax error

8
  • You may be better off generating a big sql file, and just shelling out to postgres to read it. Interacting statement-by-statement via open could get horribly complicated. Commented Apr 13, 2013 at 15:52
  • 3
    print $pipe "SELECT * FROM TheTable;\n", but you'd be better off using DBI by a large margin. What you are attempting is not sensible. Commented Apr 13, 2013 at 15:53
  • Could you elaborate one that please or maybe provide an example? Commented Apr 13, 2013 at 15:53
  • 2
    If you're asking me, the answer is no. I like you too much to be willing to inflict the pain of processing SQL via pipes in Perl. Commented Apr 13, 2013 at 15:55
  • but all i need to do is insert into a table an arbitrary number of times. Nothing more than that Commented Apr 13, 2013 at 16:06

1 Answer 1

2

Like the others say, DBI is much better than printing to a pipe.

However, there is a halfway house. Just print all your SQL to STDOUT and then do something like:

myscript.pl | psql -v ON_ERROR_STOP=1 --single-transaction -f -

This lets you easily check your script output / send it to a file. The psql options stop on the first error, wrap everything in a transaction and read from STDIN. You might want the usual -h/-U options too.

Personally, I tend to have two terminals open and just write to a .sql file then \i from a psql prompt. I like having a record of what command I ran.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.