Home > database >  How to use sql query with Curl command
How to use sql query with Curl command

Time:01-18

I have written a bash script using Curl command. I'm using an SQL query that gives a count of value 5. I want to assign that count value to T_4. Not sure how to do that in bash script using Curl command.

#!/bin/sh
result=$(
curl --netrc-file ~/.netrc -d '[
{
    "T_1": "Test1",
    "T_2": "Test2",
    "T_3": "Test3",
    "T_4": "1"
}
]' -X POST -H "Content-Type: application/json" https://www.testurl.com -d "SELECT count(5) FROM DUAL")
echo "Response from server"
echo $result
exit

Also, when I run the above script in putty, I'm getting an error that says -

"errorCode":"SIP-10322","errorMessage":"SIP-10322: rows updated is not 1:0"

Need your input on this.

The output of the SQL query which is a metric value, I have to use it in Rest call(Post API). Can anyone guide me on this?

CodePudding user response:

Use command substitution to execute the query and assign the output to a shell variable. For instance, if the DB is MySQL, you would use:

t_4=$(mysql -e "SELECT 5 FROM DUAL")

Then use the variable inside the JSON parameter.

json='[
{
    "T_1": "Test1",
    "T_2": "Test2",
    "T_3": "Test3",
    "T_4": "'$t_4'"
}
]'
result=$(curl --netrc-file ~/.netrc -d "$json" -X POST -H "Content-Type: application/json" https://www.testurl.com)
  • Related