Chinaunix

标题: 如何将数据库查询值返回给shell变量 [打印本页]

作者: hxl    时间: 2014-02-28 12:04
标题: 如何将数据库查询值返回给shell变量
我想通过shell登录数据库,然后查询某个表的记录数,让后让这个记录数返回给shell变量,请问如何实现?

select count(1)  cn from tb_test;

作者: zhaopingzi    时间: 2014-02-28 12:58
select count(1)  cn from tb_test;结果是啥?
然后通过shell单独取出值VAR
然后把VAR赋给变量
作者: q1208c    时间: 2014-02-28 14:00
  1. XXX=`echo "select count(1) cn" | mysql -u root `
  2. echo $XXX
  3. cn 1

复制代码
楼主确定这个结果是你想要的么?
作者: hxl    时间: 2014-02-28 16:07
我的是oracle,我写了如下这段怎么不行呢?

#!/bin/bash

l_last_date=`date +%Y%m%d --date="1 day ago"`


sqlplus /nolog<<ENDOFINPUT
    whenever sqlerror exit 20;
    whenever oserror exit 20;
    connect hxl/hxl;
    variable cnt number;
    begin
    select Count(1) into :cnt from tb_kettle_finish_info t where t.statedate=${l_last_date}
    if :cnt >0 then
     exit 30;
    else
     exit 40;
    end if;
    end;
/
ENDOFINPUT
echo $?
作者: q1208c    时间: 2014-02-28 16:25
oracle 太高端了, 没玩过. 不如你先试试看能不能直接输出到命令行, 然后再考虑传给变量.
作者: sohusina    时间: 2014-02-28 17:28
  1. value=`sqlplus /nolog<<ENDOFINPUT
  2.     whenever sqlerror exit 20;
  3.     whenever oserror exit 20;
  4.     connect hxl/hxl;
  5.     variable cnt number;
  6.     begin
  7.     select Count(1) into :cnt from tb_kettle_finish_info t where t.statedate=${l_last_date}
  8.     if :cnt >0 then
  9.      exit 30;
  10.     else
  11.      exit 40;
  12.     end if;
  13.     end;
  14. /
  15. exit
  16. ENDOFINPUT`

  17. echo $value
复制代码

作者: zhaopingzi    时间: 2014-02-28 18:07
回复 6# sohusina


    你的shell没问题吧




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2