【问题标题】:Retrieving data from postgreSQL with a shell script and send it by mail使用 shell 脚本从 postgreSQL 检索数据并通过邮件发送
【发布时间】:2014-06-11 11:35:20
【问题描述】:

我想每天从我的 postgreSQL 数据库中检索数据并通过邮件发送结果,请问最好的方法是什么?

我想到了一个 shell 脚本,它执行我的 SELECT,然后使用邮件功能发送它,但我不知道如何执行 SELECT 部分。

#!/bin/sh
todayDate = $(date);
nbUsers = mySelect;
nbPosts = mySelect;

echo "We are ".$date." dans there are ".$nbUsers." users and ".$nbPosts." posts " | mail -s "[DAILY]" test@test.com

编辑(更新代码):

#!/bin/sh
todayDate=$(date +%y%m%d%H%M%S)
nbUsers=$(su postgres -c "psql -d database -c 'SELECT COUNT(*) FROM table1'")
nbPosts=$(su postgres -c "psql -d database -c 'SELECT COUNT(*) FROM table2'")

echo "We are $todayDate. There are $nbUsers users and $nbPosts posts." | mail -s "[DAILY] Databse" test@test.com

EDIT2(更新代码)

#!/bin/sh
su - postgres
todayDate=$(date +"%d/%m/%y")
todayTime=$(date +"%T")
nbUsers=$(psql -A -t -d database -c "SELECT COUNT(id) FROM table1;")
nbPosts=$(psql -A -t -d database -c "SELECT COUNT(id) FROM table2;")
echo "We are $todayDate. There are $nbUsers users and $nbPosts posts." | mail -s "[DAILY] Databse" test@test.com

【问题讨论】:

标签: linux postgresql email ubuntu


【解决方案1】:

您可以使用 psql 命令从 postgresql 数据库中检索数据

nbUsers=`su postgres -c "psql -d databasename -c 'SELECT * FROM tableName'"`

之后,您可以将此命令的输出发送到邮件

【讨论】:

  • 您好,非常感谢。刚刚编辑了我的帖子以添加我的代码。我可以将您的命令分配给我的变量吗?
  • 谢谢。我更新了代码,但在执行脚本时出现错误:could not change directory to "/root"
  • 我修复了这个错误。邮件带有日期,但其他字段为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2010-12-21
  • 1970-01-01
  • 2018-02-11
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多