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

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

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


当前回答

冗长而令人费解(但请容忍我!),这里是一个类系统,我做的检查是否DB存在,并创建所需的表:

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

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

请注意 如果你不使用Visual Studio和PHP工具,不要担心这些区域,它们是用于代码折叠的

其他回答

这是我在bash脚本中做这件事的方式:

#!/bin/sh

DATABASE_USER=*****
DATABASE_PWD=*****
DATABASE_NAME=my_database

if mysql -u$DATABASE_USER -p$DATABASE_PWD -e "use $DATABASE_NAME";
then
echo "Database $DATABASE_NAME already exists. Exiting."
exit
else
echo Create database
mysql -u$DATABASE_USER -p$DATABASE_PWD -e "CREATE DATABASE $DATABASE_NAME"
fi

一个非常简单的bash一行代码:

mysqlshow | grep dbname
SELECT IF('database_name' IN(SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA), 1, 0) AS found;

另一个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...');
}

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