我需要使用Sql在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")它什么也不给我,而且tabel & file tb_data_20180502104923都没有创建。
我在哪里做错了,或者在Golang使用Sql是不可能的?如果这是不可能的,还有其他方法来满足我的需要吗?
发布于 2018-05-02 07:09:17
好吧,算了,看起来这只是我对如何使用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类型,
第二个参数-c是bash的参数,
第三个参数是我想要执行的command。
如果我错了就纠正我。
https://stackoverflow.com/questions/50127154
复制相似问题