0

This may be a trivial thing but I cannot find it anywhere... I have a variable,

UPDATED="-------------- UPDATE table SET column = 'value' WHERE condition = 'true' -------------- Query OK, 3 rows affected Rows matched: 0 Changed: 0 Warnings: 0 Bye"

I would like to get 3 from the variable $UPDATED. It could be anything, sometimes it is 0, and other times non zero (single digit, double digits, etc.)

How do I get that value of how many rows were updated. I found that using -vvv to the mysql query gives the above text and so I'm using it. If there are any other easier ways to get the count of rows updated, then even better.

2 Answers 2

1

Using grep

echo "${UPDATED}"| grep -Po  "[0-9]*(?= rows)"
Sign up to request clarification or add additional context in comments.

3 Comments

It is throwing this error, sh: 21: Syntax error: redirection unexpected
ok, seems your system doesn't support <<<, I updated , can you try again?
you have to quote variable
0

If your concern is getting the number of rows which were affected by your UPDATE statement, then you can simply use [ROW_COUNT][1] method to get that.

UPDATE table SET column = value;
SELECT row_count() INTO variable;

In your bash script, you can do this, where affected_rows is a variable which will store the value of the command

affected_rows='`mysql -h [hostname] -u[user] -p[pass] -e UPDATE table SET column = value; SELECT row_count();`';

5 Comments

This is exactly what I want but I don't know the syntax for it. I wrote as is and it is throwing an error - undeclared variable. I'm fairly new to all this so can you please help me with the exact statements?
You need to declare the variable into which you are reading the value from row_count(). So just declare the variable in your program and you would be good to go.
I'm using mysql block as follows - $MYSQL -h $MHOST -u $MUSER -p$MPASS $i << EOFMYSQL declare updated_count=0; UPDATE table SET colum = value; SELECT row_count() INTO updated_count; EOFMYSQL But it is still giving me the error ERROR 1327 (42000) at line 4: Undeclared variable: updated_count
see my edit. You don't need to know the variable name.
It is giving the entire query in echo $affected_rows as opposed to just the count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.