Abhi
Abhi

Reputation: 51

Connect to a mysql database server through a shell script

I want to write a shell script where I want to connect to a MySQL database server by providing user id and password in the shell script only and then run my drop and create database queries. The server will be in a different box-like Rubik. Any help would be highly appreciated.

Upvotes: 0

Views: 7455

Answers (1)

user1986815
user1986815

Reputation:

first you need a mysql client, install it if you don't have it

apt-get install mysql-client

then you must write like this:

#!/bin/bash
USER='username'
PASS='password'
PORT=3160
HOST='hostname'
DBASE='mysqlDbName'

Query='SELECT * FROM table WHERE some=other LIMIT 10'

mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF 
$Query
EOF

// or you simple write the MYSQL code like
mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF
USE mysql
SHOW tables
SELECT * FROM table WHERE some=other LIMIT 10
DROP table
EOF

// or in shell script and save your result to a file
#!/bin/bash
mysql -u$USER -p$PASS -h$HOST -A \
 --default-character-set=utf8 \
 -e $Query > /home/user/result.txt

Upvotes: 4

Related Questions