Shell Script SQL: Iterate Query Results

You can traverse SQL query results in a shell script using the following method:

  1. Traverse the query results using a while loop.
#!/bin/bash

# 执行SQL查询,并将结果存储到变量中
result=$(mysql -u username -p password -e "SELECT * FROM table_name")

# 将查询结果按行分割
IFS=$'\n'

# 遍历查询结果
for row in $result
do
    # 在这里处理每一行数据,可以进行各种操作
    echo $row
done
  1. Loop through the query results using a for loop.
#!/bin/bash

# 执行SQL查询,并将结果存储到变量中
result=$(mysql -u username -p password -e "SELECT * FROM table_name")

# 遍历查询结果
for row in $result
do
    # 在这里处理每一行数据,可以进行各种操作
    echo $row
done

These are two common methods to iterate through SQL query results, choose the one that best suits your needs depending on the situation.

bannerAds