是否可以在建立连接后检查MySQL数据库是否存在。

我知道如何检查一个表是否存在于一个DB,但我需要检查DB是否存在。如果不是,我必须调用另一段代码来创建它并填充它。

我知道这一切听起来有点不优雅-这是一个快速和肮脏的应用程序。


当前回答

从壳像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

其他回答

另一个php解决方案,但与PDO:

<?php
try {
   $pdo = new PDO('mysql:host=localhost;dbname=dbname', 'root', 'password', [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]);
   echo 'table dbname exists...';
}
catch (PDOException $e) {
   die('dbname not found...');
}

检查PHP中是否存在数据库的一个好方法是:

$mysql = mysql_connect("<your host>", "root", "");

if (mysql_select_db($mysql, '<your db name>')) {
    echo "Database exists";
} else {
    echo "Database does not exist";
}

这是我常用的方法。

对于那些使用php与mysqli然后这是我的解决方案。我知道答案已经回答了,但我认为这将是有帮助的答案作为一个mysqli准备的声明。

$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();

下面是一个bash函数,用于检查数据库是否存在:

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
}           

另一种选择是尝试使用数据库。注意,这也检查权限:

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

Rails代码:

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存在,entos_development1不存在