How to check if mysql database exists
SELECT SCHEMA_NAME
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE SCHEMA_NAME = 'DBName'
If you just need to know if a db exists so you won't get an error when you try to create it, simply use (From here):
CREATE DATABASE IF NOT EXISTS DBName;
From the shell like bash
if [[ ! -z "`mysql -qfsBe "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='db'" 2>&1`" ]];
then
echo "DATABASE ALREADY EXISTS"
else
echo "DATABASE DOES NOT EXIST"
fi
If you are looking for a php script see below.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Cannot use foo : ' . mysql_error());
}
A simple way to check if a database exists is:
SHOW DATABASES LIKE 'dbname';
If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.