首页 > 解决方案 > 使用 shell 脚本将数据插入 postgres db

问题描述

无法使用 shell 脚本插入包含字符的数据。下面是我的shell脚本的内容

export PGPASSWORD='postgres'; psql -h 'x.x.x.x' -U 'postgres' -d 'postgres' -c 'create table luck3 (empId int,name char(50));'
export PGPASSWORD='postgres'; psql -h 'x.x.x.x' -U 'postgres' -d 'postgres' -c 'insert into luck3 values(9,'sam');'
export PGPASSWORD='postgres'; psql -h 'x.x.x.x' -U 'postgres' -d 'postgres' -c 'insert into luck3 values(6,'ram');'

当数据类型为整数时,该命令可以正常工作,但是当我插入引号内的“sam”之类的数据时,它会引发错误:column 'sam' does not exist

标签: shell

解决方案


导出 PGPASSWORD='postgres'; psql -h 'xxxx' -U 'postgres' -d 'postgres' -c '插入luck3值(6,'sam');' 您在脚本中的任何地方都使用半引号。因此,需要在查询中对其进行转义:

-c 'insert into luck3 values(6,\'sam\');'

或者为了更好地阅读(理解)使用双引号来“转义”查询:

-c "insert into luck3 values(6,'sam');"

推荐阅读