Obtaining the Number of Rows Affected by MySQL Queries in Bash
When working with databases via the command line, it's often necessary to know how many rows are affected by an executed query. In this article, we'll explore how to capture this information while executing MySQL queries from a bash script.
Executing MySQL Queries in Bash
As mentioned by the user, there are several ways to execute MySQL queries from bash. The most common approach involves using the mysql command:
<code class="bash">mysql -u[user] -p[pass] -e "[mysql commands]"</code>
Alternatively, one can use the heredoc syntax:
<code class="bash">mysql -u[user] -p[pass] `<<`QUERY_INPUT [mysql commands] QUERY_INPUT</code>
However, neither of these methods provides direct access to the number of affected rows.
Capturing the Number of Affected Rows
To obtain the count of affected rows, we need to execute the SELECT ROW_COUNT(); statement as the last command in our batch. This statement returns the number of rows modified by the preceding statements.
Here's a modified example, based on the user's code snippet:
<code class="bash">variable='`mysql -u[user] -p[pass] -e " [mysql commands]; SELECT ROW_COUNT(); "`'</code>
By executing this command, the variable will contain both the result of the previous commands and the row count. You can then parse the variable's output to extract the desired information.
The above is the detailed content of How to Get the Number of Rows Affected by MySQL Queries in Bash?. For more information, please follow other related articles on the PHP Chinese website!