【问题标题】:How to run multiple sqlplus queries in bash loop with only 1 connection如何在只有 1 个连接的 bash 循环中运行多个 sqlplus 查询
【发布时间】:2018-01-25 22:07:21
【问题描述】:

我正在尝试使用涉及循环的 bash 脚本通过 sqlplus 传递多个 Oracle 查询。但是,我的脚本工作正常,因为它在一个循环内,它在每个循环中打开和关闭一个数据库连接。我只需要在脚本开头打开 1 个连接,然后运行我需要的所有查询,然后在脚本末尾关闭数据库连接。

这是我目前所拥有的一个例子:

#!/bin/bash

    anArrayToLoopThrough=($(sqlplus -s /nolog <<-EOF
    connect schemaname/password@database
    whenever sqlerror exit sql.sqlcode;
    set echo off feedback off verify off heading off sqlprompt '';
    select someColumn from someTable where someColumn = someValue;
    exit;
    EOF
    ))

for x in "${anArrayToLoopThrough[@]}";
    do
        someDataINeed=($(sqlplus -s /nolog <<-EOF
        connect schemaname/password@database
        whenever sqlerror exit sql.sqlcode;
        set echo off feedback off verify off heading off sqlprompt '';
        select $x from someTable where someCondition = someValue;
        exit;
        EOF
        ))
    done

我需要重新编写此代码,以免在打开/关闭数以千计的新数据库连接时发送垃圾邮件。

感谢您的任何建议。

【问题讨论】:

  • 您可以使用您的第一个查询构建一个 sqlplus 脚本,然后执行它而不是循环。这行得通吗?
  • 嗨,鲍比,谢谢您的建议。我不知道这是否对我有用,但我会尝试一下。我的脚本很复杂,有多个嵌套循环。我想我正在寻找另一种语法来打开初始连接执行一些 bash 函数、运行一些查询、执行一些 bash 函数、运行一些查询等等,而没有我用于我的 sqlplus 连接的 open-query-close 语法.
  • 每次调用sqlplus,都是一个新的进程,一个新的Oracle连接。 Bash 没有正确的结构来重用数据库连接。你必须尝试其他语言,如 Perl 或 Python 来实现你的目标。作为 Bash 中的一种解决方法,您可以在循环中生成 SQLPlus 脚本并使用它一次性调用 sqlplus
  • 你可以放弃 bash 并用 Python 编写它。 :) 实际上,也许您可​​以在 PL/SQL 中执行此操作,并在需要时调用 PL/SQL proc 或从 bash 中阻止。
  • 我现在不在命令提示符下,但在 ksh 中你可以使用 coprocess。我不确定 bash 是否有这个功能。

标签: sql linux bash oracle sqlplus


【解决方案1】:

将选择构建到一个变量中并在 for 循环之外执行它们

for x in "${anArrayToLoopThrough[@]}"; do queries="${queries}"$(echo -e "select $x from someTable where someCondition = someValue;\n") done someDataINeed=($(sqlplus -s /nolog <<-EOF "connect schemaname/password@database whenever sqlerror exit sql.sqlcode; set echo off feedback off verify off heading off sqlprompt ''; ${queries} exit; EOF ))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多