【问题标题】:Error when trying to insert values in Postgres query inside Bash script尝试在 Bash 脚本内的 Postgres 查询中插入值时出错
【发布时间】:2018-10-22 23:37:22
【问题描述】:

我正在执行如下查询:

ssh user@XX.XX.1XX.XX "PGPASSWORD=myPassword psql -U psqlUser -h XX.XX.XX.XX -p 5432 -d myDB -c
'INSERT INTO table(\"CPU_IDLE_TIME\",\"TOTAL_SIZE\",\"USED_SIZE\",\"USED_STORAGE_P\") VALUES ($idlecputime,$totalSize,$usedSize,$usedStoragePercentage)';"

我通过 snmpwalks 获得了此查询之前的值。为了使查询起作用,值必须用单引号 (' ') 括起来。我尝试在变量周围加上单引号,但每次我得到一个错误,因为查询已经被“''”包围。我似乎无法找到引号的配置或转义引号以使其工作。

变量的类型为 var char、integer 和 float。

我得到的错误之一:

ERROR:  syntax error at or near ","

提前感谢您的帮助。

【问题讨论】:

    标签: bash postgresql sql-insert


    【解决方案1】:

    使用printf 为您格式化字符串

    ssh user@XX.XX.1XX.XX "PGPASSWORD=myPassword psql -U psqlUser -h XX.XX.XX.XX -p 5432 -d myDB -c ""$(printf 'INSERT INTO table("CPU_IDLE_TIME","TOTAL_SIZE","USED_SIZE","USED_STORAGE_P") VALUES (%d, %d, %d, %d);' $idlecputime $totalSize $usedSize $usedStoragePercentage)"
    

    $() 构造在子 shell 中执行 printf。

    【讨论】:

    • 这确实有效。但我刚刚在这台服务器上安装了一个 postgres 客户端,以使事情变得更容易。谢谢!
    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 2020-11-26
    • 2020-06-29
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    相关资源
    最近更新 更多