How to check if mysql database exists
Question
Is it possible to check if a (MySQL) database exists after having made a connection.
I know how to check if a table exists in a DB, but I need to check if the DB exists. If not I have to call another piece of code to create it and populate it.
I know this all sounds somewhat inelegant - this is a quick and dirty app.
Solution
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;
OTHER TIPS
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.
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());
}
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
Here is a bash function for checking if a database exists:
function does_db_exist {
local db="${1}"
local output=$(mysql -s -N -e "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${db}'" information_schema)
if [[ -z "${output}" ]]; then
return 1 # does not exist
else
return 0 # exists
fi
}
Another alternative is to just try to use the database. Note that this checks permission as well:
if mysql "${db}" >/dev/null 2>&1 </dev/null
then
echo "${db} exists (and I have permission to access it)"
else
echo "${db} does not exist (or I do not have permission to access it)"
fi
A great way to check if a database exists in PHP is:
$mysql = mysql_connect("<your host>", "root", "");
if (mysql_select_db($mysql, '<your db name>')) {
echo "Database exists";
} else {
echo "Database does not exist";
}
That is the method that I always use.
A very simple BASH-one-liner:
mysqlshow | grep dbname
CREATE SCHEMA IF NOT EXISTS `demodb` DEFAULT CHARACTER SET utf8 ;
SELECT IF('database_name' IN(SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA), 1, 0) AS found;
For those who use php with mysqli then this is my solution. I know the answer has already been answered, but I thought it would be helpful to have the answer as a mysqli prepared statement too.
$db = new mysqli('localhost',username,password);
$database="somedatabase";
$query="SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=?";
$stmt = $db->prepare($query);
$stmt->bind_param('s',$database);
$stmt->execute();
$stmt->bind_result($data);
if($stmt->fetch())
{
echo "Database exists.";
}
else
{
echo"Database does not exist!!!";
}
$stmt->close();
Using bash:
if [ "`mysql -u'USER' -p'PASSWORD' -se'USE $DATABASE_NAME;' 2>&1`" == "" ]; then
echo $DATABASE_NAME exist
else
echo $DATABASE_NAME doesn't exist
fi
Long winded and convoluted (but bear with me!), here is a class system I made to check if a DB exists and also to create the tables required:
<?php
class Table
{
public static function Script()
{
return "
CREATE TABLE IF NOT EXISTS `users` ( `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT );
";
}
}
class Install
{
#region Private constructor
private static $link;
private function __construct()
{
static::$link = new mysqli();
static::$link->real_connect("localhost", "username", "password");
}
#endregion
#region Instantiator
private static $instance;
public static function Instance()
{
static::$instance = (null === static::$instance ? new self() : static::$instance);
return static::$instance;
}
#endregion
#region Start Install
private static $installed;
public function Start()
{
var_dump(static::$installed);
if (!static::$installed)
{
if (!static::$link->select_db("en"))
{
static::$link->query("CREATE DATABASE `en`;")? $die = false: $die = true;
if ($die)
return false;
static::$link->select_db("en");
}
else
{
static::$link->select_db("en");
}
return static::$installed = static::DatabaseMade();
}
else
{
return static::$installed;
}
}
#endregion
#region Table creator
private static function CreateTables()
{
$tablescript = Table::Script();
return static::$link->multi_query($tablescript) ? true : false;
}
#endregion
private static function DatabaseMade()
{
$created = static::CreateTables();
if ($created)
{
static::$installed = true;
}
else
{
static::$installed = false;
}
return $created;
}
}
In this you can replace the database name en
with any database name you like and also change the creator script to anything at all and (hopefully!) it won't break it. If anyone can improve this, let me know!
Note
If you don't use Visual Studio with PHP tools, don't worry about the regions, they are they for code folding :P
Rails Code:
ruby-1.9.2-p290 :099 > ActiveRecord::Base.connection.execute("USE INFORMATION_SCHEMA")
ruby-1.9.2-p290 :099 > ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development'").to_a
SQL (0.2ms) SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development'
=> [["entos_development"]]
ruby-1.9.2-p290 :100 > ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development1'").to_a
SQL (0.3ms) SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'entos_development1'
=> []
=> entos_development exist , entos_development1 not exist
IF EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = N'YourDatabaseName')
BEGIN
-- Database exists, so do your stuff here.
END
If you are using MSSQL instead of MySQL, see this answer from a similar thread.
I am using simply the following query:
"USE 'DBname'"
Then check if the result is FALSE. Otherwise, there might be an access denied error, but I cannot know that. So, in case of privileges involved, one can use:
"SHOW DATABASES LIKE 'DBname'"
as already mentioned earlier.
With this Script you can get Yes or No database exists, in case it does not exist it does not throw Exception.
SELECT
IF(EXISTS( SELECT
SCHEMA_NAME
FROM
INFORMATION_SCHEMA.SCHEMATA
WHERE
SCHEMA_NAME = 'DbName'),
'Yes',
'No') as exist
Following solution worked for me:
mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} \
-s -N -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='${MYSQL_DATABASE}'"