设为首页 收藏本站
查看: 907|回复: 0

[经验分享] perl如何访问Oracle (ZT)

[复制链接]

尚未签到

发表于 2015-12-26 15:02:56 | 显示全部楼层 |阅读模式
  http://yong321.freeshell.org/computer/OracleAndPerl.html
  Oracle and Perl
  For some programming languages, there're two general methods to access an Oracle database from the program, using the Oracle tool SQL*Plus and using the language-specific module (library). This article takes Perl as the example language.
  1. Piping to SQL*Plus
  Most programmers are unaware of this approach, partly because they're more adept at the language than the Oracle database. Taking Perl as an example, the code below shows how
#!/usr/local/bin/perl -w
open ORA, "| $ORACLE_HOME/bin/sqlplus -s $usr/$pasw" or die "Can't pipe to sqlplus: $!";
print ORA "exec mystoredprocedure\n";
print ORA "set trimspool on pagesize 500 linesize 200 colsep ''\n"
print ORA "spool output.txt\n"
print ORA "select * from mytable;\n";
print ORA "spool off\n";
print ORA "exit\n";
close ORA;
If you don't want to say print ORA every time, you can simply insert a select ORA; before the first print and say just print afterwards. Note that SQL statements have to be followed by a semicolon or slash on the next line, and then \n, enclosed in the Perl string. SQL*Plus commands such as set, exec, spool don't need to be followed by semicolon (but don't forget \n).  In a UNIX shell script, you do something similar with a here document: sqlplus -s usr/pasw <<EOF followed by SQL*Plus commands one line at a time and end with EOF. Or youecho SQL*Plus commands and pipe into sqlplus -s usr/pasw. In Tcl and Expect, you open the pipe with set ORA [ open &quot;|/thepath/sqlplus -s usr/pasw&quot; w ] and possibly with the ability to both write and read. In C, you have to use popen(3) and pclose(3) or more efficiently and securely, use pipe(2), combined with system(3). In the ostensibly powerful Java, you might get away with PipedReader and PipedWriter. I know of no way to achieve this in any flavor of BASIC including VB. However, whatever language you use, you can always launch sqlplus -s usr/pasw @sqlscript.sql arg1 arg2 at one shot, without continually injecting sql commands to sqlplus. But that may be limited in flexibility.
  (Also See two-way communication with SQL*Plus in Appendix.)
  Advantages


  • Calling SQL*Plus does not need the necessary database access module or library such as DBI. It's possible you have not installed that module or library or not installed correctly. Don't underestimate this possibility. Even a version difference between Oracle and Perl DBI module or DBD driver may stop you from using the module (driver).
  • Secondly, Oracle SQL*Plus has its superb reporting capability not many programmers are familiar with. It can break the output into sections based on the range of values for a particular column and do some calculation on each section. You would write a lot of code on your own to generate such a report, probably in a much less efficient way than Oracle does it.
  • Lastly, the output of the query is usually sent to a file especially in Perl (Perl does not support two-way piping unless you guarantee non-buffered stream as in the UNIX command cat -u, and you use IPC::Open2 or IPC::Open3; see Appendix). Writing to a file means much less memory requirement, particularly if the result set is huge. You can use Perl to process the result one line at a time by reading the output file (tip set colsep to a very uncommon character such as backtick or string so it won't occur in varchar2 text; set trimspool on). Note that calculating memory requirement purely based on array sizes is very misleading. There're a lot of factors beyond how many bytes your string takes and how many strings are in your arrays. I once worked on a project where the previous programmer wrote VB code using multiple huge multidimensional arrays to contain the query result set. The program stopped working for no apparent reason and the programmer could never reproduce the error when he worked on a small sample set. I debugged and gave up and rewrote it in Perl in about one-fifth code length and never heard any crash from our client. I spooled the result to a text file.

Disadvantages

  • The most important disadvantage may be the inability or complexity of some languages to support this approach. It may be so cumbersome, if possible, that you won't even consider launching SQL*Plus as an external command as an option. It's quite easy in most scripting languages. But I think pipes in most compiled languages are poorly supported.
  • Since you rely on SQL*Plus, you have to have that tool and probably the entire Oracle client software installed on the machine. (Of course, using the language specific module such as DBI also relies on Oracle SQL*Net, except Java thin client.)
  • With the power of SQL and SQL*Plus comes with the complexity. Most programmers know basic SQL but have very limited skills in SQL*Plus (most don't even know their difference). This is exacerbated by the demand of excellent skills in text string processing and regular expressions when you read the output file. If you predict your query result will need more and more processing in the future of your project, don't take this approach. I learned a lesson the hard way by starting a project with piping to SQL*Plus and ending with more and more time rewriting regular expressions to parse the output file, because managers kept demanding more business logic.
  • If you write the result to a file, obviously your program is slower than if you manipulate all results in memory. This is not necessarily a disadvantage, rather a trade-off between memory usage versus speed.
  2. Using a Language-Specific Module
  This is almost standard and familiar to most programmers so I won't say too much. In Perl, the example code is as follows:

use DBI;
$dbh=DBI->connect(&quot;dbi:Oracle:DBName&quot;,&quot;usr&quot;,&quot;pasw&quot;,{AutoCommit=>0}) or die &quot;Can't log in: $!&quot;;
$sth=$dbh->prepare(&quot;select mycolumn from mytable&quot;) or die &quot;$DBI::errstr&quot;;
$sth->execute or die &quot;Can't execute sth: $DBI::errstr.&quot;;
while (($mycolumn)=$sth->fetchrow_array)
{ print &quot;$mycolumn&quot; if defined $mycolumn;
}
$sth->finish;
$dbh->disconnect;
The advantages and disadvantages are just the reverse of the above mentioned.  Which approach you take depends on your project. Suppose you have a choice. The following conditions favor the first approach over the second


  • the query has only a few columns in the select list (or in the outermost select list if it contains subqueries)
  • the query returns too many rows to the extent that you suspect there's a scaleability problem
  • the query result doesn't need complicated re-processing and the processing can be easily done by sqlplus
  Appendix
  Perl only has poor support of two-way communication with an external program. This means that open ORA, &quot;| $ORACLE_HOME/bin/sqlplus -s $usr/$pasw |&quot; does not work. Instead, you have to do this (modified from the example on p.456, Programming Perl 2nd ed or p.431, 3rd ed)

use IPC::Open2;
local (*Reader, *Writer);
$pid = open2(\*Reader, \*Writer, &quot;e:/oracle/ora81/bin/sqlplus -s scott/tiger&quot;);
print Writer &quot;set pagesize 100\n&quot;;
print Writer &quot;select * from emp;\n&quot;;
print Writer &quot;exit\n&quot;;
close Writer;#have to close Writer before read
#have to read and print one line at a time
while (<Reader>)
{ print &quot;$_&quot;;
}
close Reader;
waitpid($pid, 0);#makes your program cleaner
  The above is tested on my PC using ActiveState Perl. Unfortunately, there're two limitations: the Writer has to be closed before you can read from the Reader; you can only read one line at a time. This means you can't continue to do some work in one database connection, and therefore you can't be guaranteed of single transaction consistency.
  An alternative is to use the underlying OS's support of two-way communication; specifically the support from the command line shell. You can't do it in DOS. But in UNIX, you can use here documents:

#!/usr/bin/perl -w
$s = qx{ $ORACLE_HOME/bin/sqlplus -s scott/tiger\@ORCL <<EOF
set pages 100 lines 1000 head off
select * from emp;
exit
EOF };
@lines = split /\n/, $s;
for ($i = 0; $i < scalar @lines; $i++)
{ print &quot;This is line $i: $lines[$i].\n&quot;;
}
  The operator qx// is equivalent to `` in all shells (Perl also supports ``). Note that $s is an array of all lines, as if the result set was a monolithic document slurped into $s with $/ undefed.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-156650-1-1.html 上篇帖子: DBI 数据库模块剖析:Perl DBI 数据库通讯模块规范,工作原理和实例 下篇帖子: perl文件句柄【转】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表