debugsqlMinor
can mysql cli exit with error if no records returned?
Viewed 0 times
canerrorreturnedwithrecordsexitmysqlcli
Problem
I would like to execute a sql command in bash, and do something based on whether or not there was a result.
e.g.
I can think of bodges (e.g. testing for ZLS) but wondered if there was a clean way?
e.g.
$ LOOKUP=123; mysql -e \
'SELECT id FROM table WHERE id='$LOOKUP dbname \
&& echo "Row $LOOKUP exists"
|| echo "Row $LOOKUP does not exists"I can think of bodges (e.g. testing for ZLS) but wondered if there was a clean way?
Solution
Try changing the query to force a value
Instead of
you can use
Here is bash script to use that new query
Here is an alternative
Give it a Try !!!
Instead of
SELECT id FROM table WHERE id=${LOOKUP}you can use
SELECT COUNT(1) FROM table WHERE id=${LOOKUP}Here is bash script to use that new query
LOOKUP=123
SQLSTMT="SELECT COUNT(1) FROM table WHERE id=${LOOKUP}"
RCOUNT=`mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}"`
if [ ${RCOUNT} -eq 0 ]
then
echo "Row ${LOOKUP} exists"
else
echo "Row ${LOOKUP} does not exist"
fiHere is an alternative
LOOKUP=123
SQLSTMT="SELECT CONCAT('Row ',rcount,' ',IF(rcount=0,'Exists','Does Not Exist')) FROM (SELECT COUNT(1) rcount FROM rolando WHERE id=${LOOKUP}) A"
mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}" > /tmp/answer.txt
cat /tmp/answer.txtGive it a Try !!!
Code Snippets
SELECT id FROM table WHERE id=${LOOKUP}SELECT COUNT(1) FROM table WHERE id=${LOOKUP}LOOKUP=123
SQLSTMT="SELECT COUNT(1) FROM table WHERE id=${LOOKUP}"
RCOUNT=`mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}"`
if [ ${RCOUNT} -eq 0 ]
then
echo "Row ${LOOKUP} exists"
else
echo "Row ${LOOKUP} does not exist"
fiLOOKUP=123
SQLSTMT="SELECT CONCAT('Row ',rcount,' ',IF(rcount=0,'Exists','Does Not Exist')) FROM (SELECT COUNT(1) rcount FROM rolando WHERE id=${LOOKUP}) A"
mysql -u... -p... -AN -Ddbname -e"${SQLSTMT}" > /tmp/answer.txt
cat /tmp/answer.txtContext
StackExchange Database Administrators Q#12007, answer score: 3
Revisions (0)
No revisions yet.