Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Keep a MySQL Connection Open in Bash

Tags:

bash

mysql

I have a bash script that calls MySQL several times. Instead of having to reconnect to MySQL, is there a way to keep the connection open? Ideally, the connection would close if the script exits early. I'm thinking named pipes would work but they would stay open.

Here's a quick pseudo-example of what I hope to find:


openMySQL
executeMySQL "SELECT 1"
exit 1
executeMySQL "SELECT 2"

I'm looking for the openMySQL and executeMySQL functions where the MySQL connection will actually close during the exit 1.

like image 328
User1 Avatar asked Aug 11 '10 21:08

User1


People also ask

How long does MySQL keep connection open?

MySQL has its wait_timeout variable default value set to 28800 seconds (8 hours).

Does MySQL close connection automatically?

When using something like cgi, it's completely unnecessary to close your mysql connections since they close automatically at the end of script execution.

Why do I keep losing connection to MySQL server?

The error above commonly happens when you run a long or complex MySQL query that runs for more than a few seconds. To fix the error, you may need to change the timeout-related global settings in your MySQL database server.


2 Answers

I have part of what I was looking for.

Keep the mysql connection open using fd=3 for writing:


exec 3> >(mysql)
echo "SELECT 1;" >&3
echo "SELECT 2;" >&3
exec 3>&-

Keep the mysql connection open using fd=3 for reading:


exec 3< <(echo "SELECT 1;SELECT 2;"|mysql|sed '1d')
while read <&3
do
  echo $REPLY
done

Note: sed '1d' removes the header.

Is there any way to merge these so you can write to one fd and read from another?

like image 191
User1 Avatar answered Oct 05 '22 09:10

User1


To the best of my understanding your question: coproc's available in zsh/ksh and also bash v4+ might be similar to what you have in mind, e.g.

bash4-4.1$ coproc MYSQL mysql -B -uroot 
[1] 10603
bash4-4.1$ jobs
[1]+  Running                 coproc COPROC MYSQL mysql -B -uroot &
bash4-4.1$ echo 'show databases;' | MYSQL
Database
information_schema
...

The command is kept running in the background, its stdin/stdout can accessed, it will finish (as a result its standard input closing/EOFing) as soon as the current shell exists...

like image 31
conny Avatar answered Oct 05 '22 09:10

conny