如何检查mysql数据库是否存在

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

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

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

Ankur asked 2019-02-14T03:32:17Z

17个解决方案

370 votes
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'

如果您只需要知道数据库是否存在,那么在尝试创建数据库时就不会出现错误,只需使用(从此处):

CREATE DATABASE IF NOT EXISTS DBName;
Kirtan answered 2019-02-14T03:32:28Z
97 votes

检查数据库是否存在的简单方法是:

SHOW DATABASES LIKE 'dbname';

如果名称为“dbname”的数据库不存在,则会得到一个空集。 如果确实存在,则会得到一行。

Ruben Konig answered 2019-02-14T03:32:59Z
20 votes

如果您正在寻找PHP脚本,请参阅下文。

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

TopPot answered 2019-02-14T03:33:24Z

17 votes

从像bash这样的shell

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

AskApache Webmaster answered 2019-02-14T03:33:48Z

9 votes

这是一个用于检查数据库是否存在的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 
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

docwhat answered 2019-02-14T03:34:19Z

9 votes

另一种检查数据库是否存在的最佳方法是:

$mysql = mysql_connect("", "root", "");
if(mysql_select_db('', $mysql)){
echo "databse exists";
}else{
echo "Databse does not exists";
}

这是我总是用来检查数据库是否存在的方法....

echo "rate if you enjoy :)";
Junaid Saleem answered 2019-02-14T03:34:50Z

6 votes

一个非常简单的BASH-one-liner:

mysqlshow | grep dbname
andiba answered 2019-02-14T03:35:14Z

5 votes

CREATE SCHEMA IF NOT EXISTS `demodb` DEFAULT CHARACTER SET utf8 ;
jprism answered 2019-02-14T03:35:31Z

4 votes

SELECT IF('database_name' IN(SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA), 1, 0) AS found;
Alex answered 2019-02-14T03:35:48Z

4 votes

对于那些使用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();
Thomas Williams answered 2019-02-14T03:36:13Z

4 votes

使用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
inemanja answered 2019-02-14T03:36:37Z

2 votes

IF EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = N'YourDatabaseName')
BEGIN
-- Database exists, so do your stuff here.

END

如果您使用的是MSSQL而不是MySQL,请从类似的主题中查看此答案。

deadlydog answered 2019-02-14T03:37:01Z

2 votes

漫长而曲折(但请耐心等待!),这是我用来检查数据库是否存在以及创建所需表格的类系统:

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;
}
}

在这里你可以用您喜欢的任何数据库名称替换数据库名称en,并且还可以将创建者脚本更改为任何内容(希望!)它不会破坏它。 如果有人能改进这一点,请告诉我!

注意

如果你不使用带有PHP工具的Visual Studio,不要担心区域,它们是用于代码折叠的:P

Sam Swift 웃 answered 2019-02-14T03:37:44Z

1 votes

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不存在
wxianfeng answered 2019-02-14T03:38:16Z
0 votes

以下解决方案为我工作:

mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} \

-s -N -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='${MYSQL_DATABASE}'"

Jayakumar Thazhath answered 2019-02-14T03:38:40Z

0 votes

我只使用以下查询:

"USE 'DBname'"

然后检查结果是否为FALSE。否则,可能存在拒绝访问错误,但我无法知道。因此,如果涉及特权,可以使用:

"SHOW DATABASES LIKE 'DBname'"

如前所述。

Apostolos answered 2019-02-14T03:39:19Z

0 votes

使用此脚本,您可以获得是或否数据库,如果它不存在,它不会抛出异常。

SELECT
IF(EXISTS( SELECT
SCHEMA_NAME
FROM
INFORMATION_SCHEMA.SCHEMATA
WHERE
SCHEMA_NAME = 'DbName'),
'Yes',
'No') as exist
Threading answered 2019-02-14T03:39:46Z