shell - 使用 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
。
解决方案
导出 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');"
推荐阅读
- django - Django 对象没有属性 'all'()
- php - 解释来自 Laravel Pusher 的错误
- css - 如何在显示网格中使用偏移量(边距)
- python - 使用熊猫函数将多索引名称转换为列?
- numpy - 如何用 numpy 创建这个非常规的“身份矩阵”
- amazon-web-services - 巨大的请求峰值但在 nginx 中没有记录?
- arduino - 将项目代码刷写到 CC2541 芯片的问题(使用 CCLoader)
- javascript - 在 Safari 中显示文件和行 javascript 语法错误
- postgresql - 使用值数组聚合时间序列数据
- javascript - 刷新标签时捕获加载时间