bash script to access multiple mysql databases - mysql

I all,
I have a series of MYSQL databases with different users and passwords, nevertheless the DB structure is the same for all databases.
I can't create a user with the same username and password to all of them and I need to quickly perform operations on all of them.
I was thinking about a bash script to run via cron.
Any suggestion? I was thinking to something like this but it is not working :(
#!/bin/bash
uconn=(
'mysql -u user_db1 --password=pass_db1 db1 '
'mysql -u user_db2 --password=pass_db2 db2 '
)
for f in "${uconn[#]}"
do
exec ${f}
echo `mysql show tables`
echo `mysql exit`
done
exit

Why not use the documented way?
do
${f} <<EOF
show tables
\\q
EOF
done

Just pasting the full code taking into consideration #Ansgar Wiechers:
#!/bin/bash
uconn=(
'mysql -u user_db1 --password=pass_db1 db1'
'mysql -u user_db2 --password=pass_db2 db2'
)
for f in "${uconn[#]}"
do
${f} <<EOF
show tables
\\q
EOF
done
exit
To execute the code from the local machine to the remote one this works for me:
ssh ssh_user#mydomain.com 'bash -s' < /local/path/to/multiple_db_connections.sh
where the content of multiple_db_connections.sh is the code above

Related

How to structure a cron job and script to execute sql command

I have a MySQL database accessible through CPANEL. I want to execute a SQL command to DELETE from dbtable where eventdate = 'YYYY-MM-DD'. This is my cron job.
curl -L --max-redirs 1000 -v "https://ottawaoc.ca/test/files/delete_dates.sh" 1>/dev/null
and here is the shell script
#!/bin/bash
mysql --user = "ottawaoc_test" --password = "test ps" --database = "ottawaoc_test" --execute ="DELETE FROM `h8be5_eventregistration` WHERE `eventdate` = '2020-09-27'"
(I do insert the correct password.)
I get output mailed to me and it seems to get the shell script but nothing happens within the database.
Could someone help to give me the correct commands and/or tell me how I can get errors from MySQL.
I used to run mysql crons by putting this in the shell:
#!/bin/bash
echo "mysql statement;" | mysql -B -hHOST -uUSER -pPASS DBNAME

Run mysql commands in bash script without logging in or adding -u root to every command

I'm writing a bash script to do some db stuff. New to MySQL. I'm on Mac and have MySQL installed via homebrew.
Am using username "root" right now and there isn't a pw set. I included the pw syntax below just to help others out that may have a pw.
My goal is to have mysql commands be as "clean" as possible in my bash script
Not a hige deal, but would like to do this if possible.
Example
# If I can do it without logging in (*ideal)
mysql CREATE DATABASE dbname;
# Or by logging in with - mysql -u root -pPassword
CREATE DATABASE dbname;
# Instead of
mysql -u root -pPassword -e"CREATE DATABASE dbname";
Tried to simplify it. I have a handful of things I gotta do, so would rather keep my code cleaner if possible. I tried logging in with the bash script, but the script stopped once logged into MySQL and didn't run any commands.
Another option I was considering (but don't really like) would be just to keep username and pw string in a var and call it for every commmand like so
# Set the login string variable
login_details="-u root -p password -e"
# example command
mysql $login_details"CREATE DATABASE dbname";
So any ideas?
Write a new bash script file and run this file after putting all your commands into it. Don't forget to give right username and password in your bash script.
For bash script:
#!/bin/bash
mysql -u root -pSeCrEt << EOF
use mysql;
show tables;
EOF
If you want to run single mysql command.
mysql -u [user] -p[pass] -e "[mysql commands]"
Example:
mysql -h 192.168.1.10 -u root -pSeCrEt -e "show databases"
To execute multiple mysql commands:
mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"
Note: -B is for batch, print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. -s is silent mode. Produce less output. -e is to execute the statement and quit

Executing mutiple MySQL Queries in bash script

I need to run a monthly bash script via cron that is related to our company's billing system. This is done with two stored procedures. When I run them via the MySQL console and workbench, they work fine.
I've looked at this article and this is basically the way I do it.
I call via cron, a shell script that looks like this:
mysql -h 192.168.1.1 -u<username> -p<password> mydatabase < /path/to/billing_periods.sql
My text file that has the commands in it looks like this:
call sp_start_billing_period();
call sp_bill_clients();
What happens is that the first query runs, but the second one on the second line, doesn't.
I can make a stored procedure that wraps these two - but I just was hoping to learn why this was happening... Perhaps a mistake I made or a limit in the way you do this..
I also considered doing this (two calls to the MySQL shell):
mysql -h 192.168.1.1 -u<username> -p<password> mydatabase -e "call sp_start_billing_period();"
mysql -h 192.168.1.1 -u<username> -p<password> mydatabase -e "call sp_bill_clients();"
You could try separating each statement with a semicolon.
mysql -h 192.168.1.1 -u<username> -p<password> mydatabase -e "call sp_start_billing_period();call sp_bill_clients();"
If you have your statements in a file you can do:
while read LINE; do mysql -u<username> -p<password> mydatabase -e"$LINE";echo "-----------";done < statements.sql
I think you are only allowed to execute a single statement in your input .sql file, see the mysql documentation (manpage) for -e statement.
· --execute=statement, -e statement
Execute the statement and quit. The default output format is like that produced with --batch.
The -e is implicit. At least when I do different mysql queries I put them in their own script like you already suggested.

Mysql : How to run batch of sql scripts from a folder

I have a folder with o lot of sql scripts. I want to run all of them without specifying names of them. Just specify a folder name. Is it possible?
You can not do that natively, but here's simple bash command:
for sql_file in `ls -d /path/to/directory/*`; do mysql -uUSER -pPASSWORD DATABASE < $sql_file ; done
here USER, PASSWORD and DATABASE are the corresponding credentials and /path/to/directory is full path to folder that contains your files.
If you want to filter, for example, only sql files, then:
for sql_file in `ls /path/to/directory/*.sql`; do mysql -uUSER -pPASSWORD DATABASE < $sql_file ; done
That was what worked for me:
1. Created a shell script in the folder of my scripts
for f in *.sql
do
echo "Processing $f file..."
mysql -u user "-pPASSWORD" -h HOST DATABASE < $f
done

How does MySQL take variables in bash?

Making a script to print out data from a MySQL db via bash, I met the following problem:
While I try to log in, it uses the password as the database to log in to.
Script is like this:
#!/bin/bash
echo $1
db=$1
pasx=$2
CMD="use $db; select * from job_log;"
mysql -u sqluser -p "${pasx}" -e "$CMD"
If I'm going to run the script with the command
User#server:/path/with/file$ sh sql.sh ok hobo
MySQL returns the following:
User#server:/path/with/file$ sh sql.sh ok hobo
ok
Enter password: ERROR 1049 (42000): Unknown database 'hobo'
I might have fully misunderstood something, but I can't put my finger on what it might be.
You need to remove the space after the -p parameter. See the mysql man page. You also need to specify the database in the command (remove it from the query)
mysql -u sqluser -p$pasx -e "$CMD" $db
Or maybe more clear:
mysql --user=sqluser --password=$pasx --execute="$CMD" $db
Try this:
mysql -u sqluser --password=${pasx} -e "$CMD" $db