Passing multiple parameters from shell script to mysql query - mysql

I have to write a unix shell script which will take the parameters for MySQL and export the result into csv file.
I have written to some extent but am unable to pass the multiple parameters from shell script to sql.
Can anyone help me out in this? Thanks!!

assuming you call the script like this
$ ./script param1 param2 param3
in the script
echo $0 #will echo 'script' (the name of the script)
echo $1 #will echo 'param1'
echo $2 #will echo 'param2'
echo $3 #will echo 'param3'
echo $# #will echo '3' the number of params passed to script
echo $# #will echo 'param1 param2 param3' (all the parameters passed)
host="127.0.0.1"
user="root"
password="pass"
result=`mysql -h $host --user=$user --password=$password --skip-column-names -e "select $param1 from $param2 where $param3 = 3"`
echo $result

mysql -e "set #param1:=4897, #param2:=2; source the_script.sql;"
And the script:
SELECT #param1, #param2;
P.S. BTW, I recommend to pass connection parameters using --defaults-extra-file option.

Related

Redirecting mysql output to prompt using shell

I'm writing a shell code to automaticaly run multiple sql queries in multiple databases. My code is working well, but beside "select" queries, all other queries aren't displaying anything in the prompt while executing. How could I force query outputs to redirect to prompt?
That's some of my code:
for x in "${db[#]}"
do
found=0
for enreg in `cat /home/dbfile.csv`
do
#extracting database data from csv
DBNAME=`echo $enreg | awk -F";" '{ print $4 }'`
if [ $x = $DBNAME ]
then
PASS=`echo $enreg | awk -F";" '{ print $2 }'`
HOST=`echo $enreg | awk -F";" '{ print $3 }'`
USERNAME=`echo $enreg | awk -F";" '{ print $1 }'`
# Running queries in database $DBNAME
for y in "${req[#]}"
do
echo "
"
mysql -u $USERNAME -p$PASS -h $HOST $DBNAME -e "$y"
echo "
"
done
found=1
break
fi
done
if [ $found -eq 0 ]
then
echo "Database $x doesn't exist"
fi
done

How do not remove leading zero from variable in a Bash MySQL query?

I am trying to query against the database to validate if a registry exists. I created I bash script to make that:
read -p "`echo $'\n '`-------------`echo $'\n '` Insert a CPF: `echo $'\n '`-------------`echo $'\n '`" CPF
USER_IN_OPTOUT=$(mysql -u $BMB_MYSQL_USER -h $BMB_MYSQL_HOST -NB -se "SELECT cpf FROM optout WHERE cpf = $CPF;")
if [[ ${USER_IN_OPTOUT} == *"${CPF:0}"* ]]; then
echo "----------------------------------------"
echo "User already exists."
echo "----------------------------------------"
else
echo "---------------------------------------"
echo "User does not exists."
echo "---------------------------------------"
exit 1
fi
The variable CPF ($CPF) is equal to 00324323721. As this registry exists it returns the cpf, as expected. However, this query is removing leading zeros returning 324323721. I expect that the returns be exactly 00324323721. How can I do that?

insert sql record by command line ssh

i try to execute this command line:
ssh root#ip "mysql -u login -ppassword zabbix -e
'INSERT INTO worldmap_latlng (lat,lng,name,value,timestamp)
VALUES (48.891198, 2.2465829, "'test'", 0, now())'"
but i have this response :
ERROR 1054 (42S22) at line 1: Unknown column 'test' in 'field list'
i try with ' and " but not work
you can do that using ssh and bash combo
write bash file on remote machine say insert.sh in ./ path location
#!/bin/bash
lat= echo $1
lng= echo $2
name= echo $3
value= echo $4
# echo $lat
# echo $lng
# echo $name
# echo $value
echo "insert into worldmap_latlng (lat,lng,name,value) values $lat , '$lng', '$name' , '$value' ;" #| mysql -ulogin -ppassword zabbix
exit
ssh root#ip sh ./insert.sh latval lngval nameval valueval
You can also write some python or other languages script that takes args and insert and execute that using ssh

conditional statement in bash with mysql query

im trying to write a bash script that will do a mysql query and if the number of results is 1, do something. i cant get it to work though.
#!/bin/sh
file=`mysql -uroot -proot -e "select count(*) from MyTable.files where strFilename='file.txt'"`
if [[ $file == "count(*) 1" ]];
then
echo $file
else
echo $file
echo "no"
fi
i verified the query works. i keep getting this returned
count(*) 1
no
im not sure why but i think it might have something to do with the type of variable $file is. any ideas?
To prevent exposing your database credential in the script you can store them in the local .my.cnf file located in your home directory.
This technic will allow your script to work on any server without modification.
Path: /home/youruser/.my.cnf
Content:
[client]
user="root"
password="root"
host="localhost"
[mysql]
database="MyTable"
So, Renato code could be rewritten by following:
#!/bin/sh
file=`mysql -e "select count(*) as count from files where strFilename='file.txt'" | cut -d \t -f 2`
if [ $file == "1" ];
then
echo $file
else
echo $file
echo "no"
fi
I rewrote your script, it works now:
#!/bin/sh
file=`mysql -uroot -proot -e "select count(*) as count from MyTable.files where strFilename='file.txt'" | cut -d \t -f 2`
if [ $file == "1" ];
then
echo $file
else
echo $file
echo "no"
fi
I'm giving a better name to the count field, using 'cut' to split the mysql output into two fields and putting the content of the second field into $file. Then you can test $file for "1". Hope it helps you..
I'm guessing that isn't actually count(*) 1 but instead count(*)\n1 or something. echo $file will convert all the characters in IFS to a space, but == will distinguish between those whitespace characters. If this is the case, echo "$file" will give you a different result. (Notice the quotes.)

What's a Good Way to Commit All MySQL Settings Needed to Get a Django App Running?

I'm in the middle of making my first django app, and I'd like to commit it to git in such a way that someone can clone it down and start working on it with the least amount of trouble. One of the things I needed to do to get things up and running was to create a new db in my local mysql installation and create a new user there. I'd love to let someone clone things down and have that done automatically for them. Is there a good way to do this?
Use mysql-python and write a python script to create the database or alter my shell script to make it suit your needs.
#!/bin/bash
function pre_checks() {
if [[ "$1" -ne 3 ]]; then
echo "Usage: $0 [DATABASE NAME] [USERNAME] [HOST]"
return 1
fi
if ! command -v /usr/bin/mysql >/dev/null 2>&1; then
echo "Mysql is not installed."
return 1
fi
echo -n "Create the database '${2}' and the user '${3}' now? (y/n) "
read ANSWER
case "$ANSWER" in
"y"|"Y")
echo -n "Password for ${3}: "
read -s USER_PW
echo
return 0 ;;
"n"|"N"| *)
echo "Bye."
return 1 ;;
esac
}
function create_db() {
Q1="CREATE DATABASE IF NOT EXISTS ${1} CHARACTER SET utf8;"
Q2="GRANT ALL ON *.* TO '${2}'#'${3}' IDENTIFIED BY '$USER_PW';"
Q3="FLUSH PRIVILEGES;"
Q4="SHOW DATABASES;"
SQL="${Q1} ${Q2} ${Q3} ${Q4}"
echo "Query:"
echo "${SQL}"
echo -n "Run query now? (y/n) "
read ANSWER
case "$ANSWER" in
"y" | "Y" )
/usr/bin/mysql -uroot -p -e "$SQL" || echo "Failure."
;;
"n" | "N" | *)
echo "Bye."
return 1
;;
esac
}
pre_checks "$#" "$1" "$2" && create_db "$1" "$2" "$3"