【问题标题】:Execute SQL Plus Command in Golang在 Golang 中执行 SQL Plus 命令
【发布时间】:2018-05-02 15:15:40
【问题描述】:

我需要使用 Sql Plus 在 Golang 中运行一个 .sql 文件,它会创建一个表和一个名为 tb_data_20180502104923 的文件。我将.sql脚本命名为tb_data_20180502104923.sql,内容如下:

set headsep off
set pagesize 0
set trimspool on
set trimout on
create table tb_data_20180502104923
as
select * from tb_data;
spool tb_data_20180502104923.txt
SELECT data_id||';'||data_content FROM tb_data_20180502104923;
spool off

我已经用os/exec 尝试过这样的:

func main(){
    cmd := exec.Command("sqlplus -s admin/123#@172.10.1.211:1521/orcl < tb_data_20180502104923.sql")

    var out, stderr bytes.Buffer

    cmd.Stdout = &out
    cmd.Stderr = &stderr

    err := cmd.Run()
    if err != nil {
        log.Fatalf("Error executing query. Command Output: %+v\n: %+v, %v", out.String(), stderr.String(), err)
    }
}

返回错误信息:

2018/05/02 11:06:46 Error executing query. Command Output: 
: , fork/exec sqlplus -s admin/123#@172.10.1.1:1521/orcl < tb_data_20180502104923.sql: no such file or directory
exit status 1

如果我将cmd := exec.Command 语句更改为:

cmd := exec.Command("sqlplus", "-s", "admin/123#@172.10.1.211:1521/orcl", "< tb_data_20180502104923.sql")

它什么也没给我,表和文件tb_data_20180502104923 都没有创建。

我在哪里做错了,或者在 Golang 中无法使用 Sql Plus?如果不可能,还有其他方法可以做我需要的吗?

【问题讨论】:

  • 要在 go 中运行命令 sqlplus user/pass@connect @scriptname,请尝试 exec.Command("sqlplus", "user/pass@connect", "@scriptname")
  • 感谢您的评论马克,但我已经解决了我自己的问题。这只是我的理解力差。我已经在下面发布了这个问题的解决方案

标签: go sqlplus


【解决方案1】:

好吧,没关系,看来这只是我对如何使用os/exec的理解不足。

所以如果有人不知道如何使用它,这里我如何解决我自己的问题。

我变了

cmd := exec.Command("sqlplus", "-s", "admin/123#@172.10.1.211:1521/orcl", "< tb_data_20180502104923.sql")

cmd := exec.Command("bash", "-c", "sqlplus -s admin/123#@172.10.1.211:1521/orcl < tb_data_20180502104923.sql")

第一个参数bash是你要使用的Shell类型,

第二个参数-cbash的参数,

第三个参数是我要执行的command

好吧,如果我错了,请纠正我。

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 2015-03-07
    • 2014-04-10
    相关资源
    最近更新 更多