简体   繁体   English

如何通过Perl脚本运行sql(.sql文件)

[英]how to run a sql(.sql file) via perl script

Hi i have a sql file(test.sql) something as simple as , 嗨,我有一个sql文件(test.sql),简单得像,

select emp_id from employees 
where country='xxx'
and department='sales'

i know how to call this sql using a shell script, we normally use 我知道如何使用Shell脚本调用此sql,我们通常使用

#/bin/ksh

sqlplus $login $password test.sql

so my shell will call this sql and i spool this into a file. 所以我的外壳程序将调用此sql,并将其后台打印到文件中。 But how to do the same using a perl script. 但是如何使用perl脚本执行相同的操作。

I'm totally new to perl script and any help is greatly appreciated. 我是Perl脚本的新手,任何帮助都将不胜感激。

You won't be able to directly execute the sql file without first writing a perl script which takes the path to your sql file as a parameter then executes it. 您必须先编写将SQL文件的路径作为参数然后执行它的Perl脚本,才能直接执行该SQL文件。 Here is a question which explains how to do (in perl): 这是一个解释如何做的问题(在perl中):

Execute SQL file in Perl 在Perl中执行SQL文件

However, if you just want to execute the sql file there are easier ways to do that. 但是,如果您只想执行sql文件,则有更简单的方法可以执行该操作。 Feel free to clarify exactly what you are trying to accomplish other than executing this with perl instead of ksh - we might be able to provide more insight :). 除了使用perl而不是ksh来执行此操作外,您可以随意澄清您要完成的工作-我们也许可以提供更多的见解:)。

On a very basic level you could just call a system command as shown below. 在非常基本的级别上,您可以如下所示调用系统命令。

Assuming your Oracle environment variables are set up in the user and sqlplus can be found on the $PATH 假设您在用户中设置了Oracle环境变量,并且可以在$ PATH上找到sqlplus

my $login     = "fred";
my $password  = "secretword";
my $sqlfile   = "/path/to/test.sql";

my @sql_array = system("sqlplus $login $password $sqlfile");

I chose to store the results in an array so that you could traverse each element (row) in turn 我选择将结果存储在数组中,以便可以依次遍历每个元素(行)

foreach my $row ( @sql_array )
{
    print $row;
}

There may be much better ways to do this but keeping it basic when learning Perl, I always found the system() command to be a good friend. 可能有更好的方法来执行此操作,但在学习Perl时将其保持基础,我总是发现system()命令是一个很好的朋友。 Using Perl arrays is my chosen method of reading in output from a system command. 使用Perl数组是我选择的从系统命令读取输出的方法。

You may find other bits of spurious data in the array (sqlplus but you can prune these out with regular expressions in the foreach loop. 您可能会在数组中找到其他虚假数据位(sqlplus,但可以在foreach循环中使用正则表达式对它们进行删节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM