Home > Database > Mysql Tutorial > How to Get the Number of Rows Affected by MySQL Queries in Bash?

How to Get the Number of Rows Affected by MySQL Queries in Bash?

Susan Sarandon
Release: 2024-10-31 00:48:02
Original
432 people have browsed it

How to Get the Number of Rows Affected by MySQL Queries in Bash?

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

Alternatively, one can use the heredoc syntax:

<code class="bash">mysql -u[user] -p[pass] `<<`QUERY_INPUT

[mysql commands]

QUERY_INPUT</code>
Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template