开发者

Open a piped process (sqlplus) in perl and get information from the query?

Basically, I'd like to open a pipe to sqlplus using Perl, sending a query and then getting back the information from the query.

Current code:

open(PIPE, '-|', "sqlplus user/password@server_details");

while (<PIPE>) {
    print $_;
}

This allows me to jump into sqlplus and run my query.

What I'm having trouble figuring out is how to let Perl send sqlplus the query (since it's always the same query), and once that's done, how can I get the information written back to a variable in my Perl script?

PS - I know about DBI... but I'd like to know how to do it using the above method, as inelegant as it is :)


Made some changes to the code, and I can now send my query to sqlplus but it disconnects... and I don't know how to get the res开发者_运维技巧ults back from it.

my $squery = "select column from table where rownum <= 10;"

# Open pipe to sqlplus, connect to server...
open(PIPE, '|-', "sqlplus user/password@server_details") or die "I cannot fork: $!";
# Print the query to PIPE?
print PIPE $squery;

Would it be a case of grabbing the STDOUT from sqlplus and then storing it using the Perl (parent) script?

I'd like to store it in an array for parsing later, basically.

Flow diagram:

Perl script (parent) -> open pipe into sqlplus (child) -> print query on pipe -> sqlplus outputs results on screen (STDOUT?) -> read the STDOUT into an array in the Perl script (parent)


Edit: It could be that forking the process into sqlplus might not be viable using this method and I will have to use DBI. Just waiting to see if anyone else answers...


Forget screen scraping, Perl has a perfectly cromulent database interface.


I think you probably want IPC::Run. You'll be using the start function to get things going:

 my $h = start \@cat, \$in, \$out;

You would assign your query to the $input variable and pump until you got the expected output in the $output variable.

$in = "first input\n";

## Now do I/O.  start() does no I/O.
pump $h while length $in;  ## Wait for all input to go

## Now do some more I/O.
$in = "second input\n";
pump $h until $out =~ /second input/;

## Clean up
finish $h or die "cat returned $?";

This example is stolen from the CPAN page, which you should visit if you want more examples.


If your query is static consider moving it into it's own file and having sqlplus load and execute it.

open(my $pipe, '-|', 'sqlplus', 'user/password@server_details', '@/path/to/sql-lib/your-query.sql', 'query_param_1', 'query_param_2') or die $!;

while (<$pipe>) {
    print $_;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜