SnapLogic Python读取和执行SQL-Fi

2024-06-10 15:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的SQL文件,我想用Python脚本管理单元SnapLogic来读取和执行它。我创建了一个表达式库文件来引用Redshift帐户,并将其作为参数包含在管道中。在

我有另一个帖子的代码。有没有方法可以引用pipeline参数来连接到Redshift数据库,读取上传的SQL文件并执行命令?在

fd = open('shared/PythonExecuteTest.sql', 'r')
sqlFile = fd.read()
fd.close()

sqlCommands = sqlFile.split(';')

for command in sqlCommands:
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Tags: 文件脚本redshiftsql参数管道表达式msg
1条回答
网友
1楼 · 发布于 2024-06-10 15:35:49

可以使用$_访问脚本中的管道参数。

假设有一个管道参数executionId。然后要在脚本中访问它,可以执行$_executionId

下面是一个测试管道。

pipeline

使用以下管道参数。

Pipeline parameter

以下是测试数据。

test data

以下是脚本

# Import the interface required by the Script snap.
from com.snaplogic.scripting.language import ScriptHook
import java.util

class TransformScript(ScriptHook):
    def __init__(self, input, output, error, log):
        self.input = input
        self.output = output
        self.error = error
        self.log = log

    # The "execute()" method is called once when the pipeline is started
    # and allowed to process its inputs or just send data to its outputs.
    def execute(self):
        self.log.info("Executing Transform script")
        while self.input.hasNext():
            try:
                # Read the next document, wrap it in a map and write out the wrapper
                in_doc = self.input.next()
                wrapper = java.util.HashMap()
                wrapper['output'] = in_doc
                wrapper['output']['executionId'] = $_executionId

                self.output.write(in_doc, wrapper)
            except Exception as e:
                errWrapper = {
                    'errMsg' : str(e.args)
                }
                self.log.error("Error in python script")
                self.error.write(errWrapper)

        self.log.info("Finished executing the Transform script")

# The Script Snap will look for a ScriptHook object in the "hook"
# variable.  The snap will then call the hook's "execute" method.
hook = TransformScript(input, output, error, log)

输出:

output

在这里,您可以看到executionId是从管道参数中读取的。

注意:从脚本访问管道参数是一个有效的方案,但是从脚本访问其他外部系统非常复杂(因为您需要加载所需的库),因此不建议这样做。使用SnapLogic提供的快照访问外部系统。另外,如果您想在脚本中使用其他库,请尝试使用Javascript而不是python,因为您可以在脚本中使用许多开源cdn。

此外,您不能直接从脚本访问任何配置的表达式库。如果脚本中需要一些逻辑,可以将其保存在脚本中,而不是其他地方。而且,访问脚本(或映射器)中的帐户名是没有意义的,因为即使知道帐户名,也不能直接使用存储在该帐户中的凭据/配置;这是由SnapLogic处理的。尽可能使用提供的快照和映射器。


更新1

  • 您不能直接访问帐户。帐户由快照在内部管理和使用。只能通过相关快照的“帐户”选项卡创建和设置帐户。在
  • 尽量避免使用脚本捕捉;尤其是如果可以使用普通捕捉执行相同的操作。在

更新2

对于这一要求,最简单的解决方案如下。

  • 使用文件读取器读取文件
  • 基于;拆分
  • 使用通用JDBC ExecuteSnap执行每个SQL命令

相关问题 更多 >