shell 遍歷mysql查詢結果的四種方式,建議收藏

# 定義資料庫連線資訊

HOST_NAME=localhost

DB_NAME=sima

USER_NAME=suda

PASSWD=‘111111’

# -s 去掉表頭

MYSQL_ETL=“mysql -h $HOST_NAME -P4045 -D$DB_NAME -u$USER_NAME -p$PASSWD -s -e”

# 這裡是從mysql裡查詢出來的結果,然後遍歷

ssql=“SELECT hive_table from sima_sports_event_hive_column where status = 0 GROUP BY hive_table”

shell 遍歷mysql查詢結果的四種方式,建議收藏

方式1、直接把結果賦值給變數,然後迴圈變數(多行多列的結果會變成1行,一個一個遍歷)

hive_table=$($MYSQL_ETL “${ssql}”)

echo $hive_table

for table in $hive_table

do

echo $table

done

方式2、把結果放到檔案中,然後把檔案cat放到變數中(多行多列的結果會變成1行,一個一個遍歷)

$MYSQL_ETL “${ssql}” >temp。txt

tempt=$(cat temp。txt)

for table in $tempt

do

echo $table

done

方式3、適用於多個欄位的時候按行讀取 但是res的不會在迴圈中被賦值

res=””

cat temp。txt | while read line

do

res=`echo $line |awk ‘{print $1}’`

echo $line

done

echo $res

方式4、適用於多個欄位的時候按行讀取,res的會被賦值!

while read line

do

res=`echo $line |awk ‘{print $1}’`

echo $line

done < temp。txt

注意:mysql查出來放到temp。txt檔案裡的資料,列之間是 \t 分隔的

而到了 while read line 中, 使用`echo $line |awk -F” “‘{print $1}’` 預設是按照空格分隔的

文章轉載:https://www.wangt.cc/2017/08/shell-%e9%81%8d%e5%8e%86mysql%e6%9f%a5%e8%af%a2%e7%bb%93%e6%9e%9c-%e5%9b%9b%e7%a7%8d%e6%96%b9%e5%bc%8f/

最後,特別推薦一個分享C/C++和演算法的優質內容,學習交流,技術探討,面試指導,簡歷修改...還有超多原始碼素材等學習資料,零基礎的影片等著你!

點選下方“瞭解更多”