Home > Software engineering >  How to check if MySQL service is running with DBD::mysql
How to check if MySQL service is running with DBD::mysql

Time:11-23

I am using the following DBD::mysql statement to connect to a MySQL database:

use DBI;
 
# Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",
                       "usr", "usr's password",
                       {'RaiseError' => 1});

Is there a way to check if MySQL service is running, before trying to connect to the database? What if the database is running on a remote server?

CodePudding user response:

If you want a solution to check if the service is running without attempting to connect to it, you could use some Perl package to check the process table (works locally only), or check that the MySQL port (3306 by default) has a process listening to it.

I'm not sure what the purpose of this check is, because even if the service is running, the next thing you'll probably want to do is open a DB connection. Opening a DB connection is a quick and easy thing to do, and it has good error reporting if it doesn't work. So your intention to check that the service is running first is just unnecessary overhead.

I would just try to connect as you are doing. This is the most direct way of checking that the service is running, and it works both locally and remotely.

If there's an error, catch the error and interpret the error message. It'll be error 2002 (for localhost) or 2003 (for TCP/IP, whether it's the same host or a remote host).

These errors are mostly reliable. But there could be red herrings, for example if the service is running on a remote host, but your client host can't reach it because of firewalls or routing issues.

If you get an error 1045 (Access Denied), at least you know the service is running and you can reach it, the problem is only that your user & password are incorrect, or you tried to access a schema you don't have privilege to use.

  • Related