Home  >  Article  >  Database  >  How to Capture the Number of Rows Affected by a MySQL Query in Bash?

How to Capture the Number of Rows Affected by a MySQL Query in Bash?

DDD
DDDOriginal
2024-10-31 02:24:01583browse

How to Capture the Number of Rows Affected by a MySQL Query in Bash?

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:

  1. Execute the query:
variable=`mysql -u[user] -p[pass] -e "[mysql commands]"`
  1. Extract the last line:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn