Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-10-31 02:24:01
Original
583 people have browsed it

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]"
Copy after login

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();
Copy after login

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]"`
Copy after login
  1. Extract the last line:
row_count=`echo "$variable" | tail -n1`
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!