Capturing the Number of Rows Affected during MySQL Queries in Bash
Executing MySQL queries from the bash command line is commonly done using commands like:
mysql -u[user] -p[pass] -e "[mysql commands]"
However, capturing the number of rows affected by a query requires an additional step.
Using ROW_COUNT()
To retrieve the number of affected rows, append the following statement to your MySQL query:
SELECT ROW_COUNT();
This statement will return the number of modified rows.
Parsing the Output
The output of the query will contain both the query result and the row count. To parse the row count, you can use the following steps:
variable=`mysql -u[user] -p[pass] -e "[mysql commands]"`
row_count=`echo "$variable" | tail -n1`
Example Usage:
# Execute query and capture row count result=`mysql -u[user] -p[pass] -e "UPDATE table_name SET column_name='new value' WHERE condition;" | tail -n1` # Print row count echo "Number of rows affected: $row_count"
The above is the detailed content of How to Capture the Number of Rows Affected by a MySQL Query in Bash?. For more information, please follow other related articles on the PHP Chinese website!